ch11_Exception
Download
Report
Transcript ch11_Exception
Exception: Java Error Handling
Yingcai Xiao
Error Handling
In-line
if(error) System.out.println(“Error occurred here.”);
Block-based
if(error) {
ErrorCode = ErrorTypeOne;
goto ErrorHandlingBlock;
}
…
ErrorHandlingBlock:
switch(ErrorCode){
case ErrorTypeOne:
…
break;
…
}
Error Handling
Function-based
if(error) ErrorHandlingFunction(ErrorCode);
Event-based & Object-oriented
An event is generated when an error occurs. Event handling
functions are error handling functions registered to handle “error”
events.
In Java, an error event is called an exception. Error handling
functions are called exception handlers. An object that describes an
error is called an exception object.
An exception is an unexpected condition preventing the
normal execution of the code.
Note: some errors are expected conditions. For example, the
user gives an out-of-range input.
Exception Based Error Handling
1. Create an exception object when an error condition occurs.
2. “throw” the exception object.
3. Current path of execution is stopped.
(done by the Java Interpreter)
1. Execution “jumps” to a registered exception handler (the nearest
one and go no further). (done by the Java Interpreter)
2. The event handler handles the error and determines the path of
continuation.
e.g.:
MyObject o = new MyObject();
if(o == null) throw new NullPointerException();
Exception Based Error Handling
Note:
• Exceptions can be “throw”ed anywhere in the code.
• Exception handlers can be defined anywhere as needed.
• Low level library methods may throw exceptions but expecting
the methods’ users to handle the exceptions.
• Standard Java exceptions can be found at java.sun.com.
• When overriding a method, you can throw only the
exceptions that have been specified in the base-class
version of the method.
Using a New Exception Class
public static void main(String[] args) {
SimpleExceptionDemo sed =
new SimpleExceptionDemo();
try {
sed.f(); // exceptions thrown out from f
} catch(SimpleException e) {
System.err.println("Caught it!");
}
}
} ///:~
Some Methods in the Exception Class
Exception is a child of throwable, which in
turn is a child of Object.
String getMessage( )
String getLocalizedMessage( )
String toString( )
void printStackTrace( )
void printStackTrace(PrintStream)
void printStackTrace(PrintWriter)
Class getClass( )
Rethrowing an Exception
Rethrowing an exception causes the exception to go to
the exception handlers in the next-higher context.
catch(Exception e) {
System.err.println("An exception was thrown");
throw e;
}
Performing cleanup with finally
try {
// The guarded region: Dangerous activities
// that might throw A, B, or C
} catch(A a1) {
// Handler for situation A
} catch(B b1) {
// Handler for situation B
} catch(C c1) {
// Handler for situation C
} finally {
// Activities that happen every time
// regardless exceptions are thrown or not
}