finally
[13/22]pseudocode:At first glance this function seems simple enough, but it ignores all of these potential errors:readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }Your function would end up looking something like this:
- What happens if the file can't be opened?
- What happens if the length of the file can't be determined?
- What happens if enough memory can't be allocated?
- What happens if the read fails?
- What happens if the file can't be closed?
errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }versus the Java style:
readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } }
Old style:Suppose thatmethod1 { call method2; } method2 { call method3; } method3 { call readFile; }method1
is the only method interested in the errors that occur withinreadFile
. Traditional error notification techniques forcemethod2
andmethod3
to propagate the error codes returned byreadFile
up the call stack until the error codes finally reachmethod1
Java style:method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; }method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }
-Exceptions are first-class objects in Java
-Allowing for better error handling depending on the specifications of the particular error, which can be very unique, and even more so if you define your own.
-For example, in the following diagram,ArrayException
is a subclass ofException
(a subclass ofThrowable
) and has three subclasses.- InvalidIndexException
,ElementTypeException
, andNoSuchElementException
are all leaf classes. Each one represents a specific type of error that can occur when manipulating an array.
-You can have acatch
statement for each one of them
public int myMethod(String s) throws MyOwnException { ... }
try
{ some code that might throw exceptions
} catch (SomeException e)
{ code to deal with exception }
finally
[13/22]finally
clause
try
or catch
code
try
{ f = new FileReader("test");
System.out.println(f.read());
}
catch (FileNotFoundException e)
{ System.err.println("Not found!"); }
catch (IOException e)
{ System.err.println("IO problem!"); }
finally
{ if (f!=null) f.close(); }
- InterruptedException
- Thread.sleep
- ClassNotFoundException
- Class.forName
- SQLException
- DriverManager.getConnection
- Statement.executeQuery
- Statement.executeUpdate
try { ... } finally { ... }
What is wrong with using this type of exception handler?catch (Exception e) { ... }
Is there anything wrong with this exception handler as written? Will this code compile?... } catch (Exception e) { ... } catch (ArithmeticException a) { ... }
try { return 2; } finally { return 3; }
Answer: Yes, it's legal. Atry { ... } finally { ... }
try
statement does not have to have
a catch
statement if it has
a finally
statement.
If the code in the try
statement has multiple
exit points and no associated catch
clauses,
the code in the finally
statement is executed no matter how the try
block is exited.
What is wrong with using this type of exception handler?catch (Exception e) { ... }
Answer:
This handler catches exceptions of type Exception
;
therefore, it catches any exception.
This can be a poor implementation
because you are losing valuable information
about the type of exception being thrown
and making your code less efficient.
As a result, the runtime system is forced to determine the
type of exception
before it can decide on the best recovery strategy.
Is there anything wrong with this exception handler as written? Will this code compile?... } catch (Exception e) { ... } catch (ArithmeticException a) { ... }
Answer:
This first handler catches exceptions of type Exception
;
therefore, it catches any exception,
including ArithmeticException
.
The second handler could never be reached.
This code will not compile.
Answer: 3, the try will complete correctly, but before any value is actually returned, finally will run and its return statement will be returned.try { return 2; } finally { return 3; }
javadoc *.java
Text intended for javadoc must be placed in doc-comments that begin with /**
and end with */
.
Doc-comments for a class or method must be placed immediately before the class or method declaration.
The first sentence for a doc-comment should be a one-sentence summary of the class or method being documented.
@author
name-text
@deprecated
deprecated-text
@exception
class-name description
{@link
name label}
@param
parameter-name
description
@return
description
@see
reference
@serial
field-description
An optional field-description augments the doc comment for the field. The combined description must explain the meaning of the field and list the acceptable values.
@serialData
data-description
writeObject
method and all data written by the
Externalizable.writeExternal
method.
The @serialData
tag can be used in the doc comment
for the writeObject
, readObject
,
writeExternal
, and readExternal
methods.
@serialField
field-name field-type field-description
ObjectStreamField
component of a
Serializable
class' serialPersistentFields
member. One @serialField
tag should be used for
each ObjectStreamField
component.
@since
since-text
@throws
class-name description
@throws
and @exception
tags are synonyms.
Adds a "Throws" subheading to the generated documentation, with
the class-name and description text.
The class-name is the name of the exception that may
be thrown by the method. If this class is not fully-specified,
javadoc uses the search order to look up this class.
@version
version-text
@version
tag. Version normally refers to the version
of the software (such as the JDK) that contains this class or member.