Saturday 3 August 2013

27:Exception Handling

Learning Objectives
After completing this session, you will be able to:
‰  Define an exception
‰  Identify what happens whenan exception occurs
‰  List the benefits of Exception Handling framework
‰  Catch exceptions with try-catch and finally
Exception
Exceptional event
Error that occurs during run-time
Cause normal program flow to be disrupted
Examples are:
‰  Divide by zero errors
‰  Accessing the elements of an array beyond its range
‰  Invalid input
‰  Hard disk crash
‰  Opening a file that does not exist
‰  Heap memory exhausted
Exception Example
1 class DivByZero {
2 public static void main(String args[]) {
3 System.out.println(3/0);
4 System.out.println(“Pls. print me.”);
5 }
6 }
Example: Default Exception Handling
Displays this error message:
Exception in thread "main“ java.lang.ArithmeticException: / by zero at
DivByZero.main(DivByZero.java:3)
Default exception handler:
‰  Provided by Java run time
‰  Prints out exception description
‰  Prints the stack trace: Hierarchy of methods where the exception occurred
‰  Causes the program to terminate
What Happens when an Exception Occurs?
‰  When an exception occurs within a method,the method creates an exception object
and hands it off to the run-time system:
‰  Creating an exception object and handing it tothe run-time system is called “throwing
an exception”.
‰  Exception object contains information about the error, including its type and the state
of the program when the error occurred.
‰  The run time system searches the call stack for a method that contains an exception
handler.

‰  When an appropriate handler is found, the run-time system passes the exception to
the handler:
‰  An exception handler is considered appropriate if the type of the exception object
thrown matches the type that can be handled by the handler.

‰  The exception handler chosen is said to catch the exception.
‰  If the run-time system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, then the run-time system (and,
consequently, the program) terminates and uses the default exception handler.
Searching the Call Stack for an Exception Handler
Sample diagram representing the Exception handling framework
Benefits of Java Exception Handling Framework
The benefits of Java Exception Handling Framework are:
‰  Separating Error-Handling code from “regular” business logic code
‰  Propagating errors up the call stack
‰  Grouping and differentiating error types
Separating Error Handling Code from Regular Code
In traditional programming, error detection, reporting, and handling often lead to confusing
spaghetti code.
Consider the pseudo code method here that reads an entire file into memory:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}

Exception Class Hierarchy
The Throwable, Exception, and Error classes:
Throwable class:
‰  Root class of exception classes
‰  Immediate subclasses:
‰  Error
‰  Exception
Exception class:
‰  Conditions that user programs can reasonably deal with
‰  Usually the result of some flaws in the user program code
‰  Examples:
oDivision by zero error
oArray out-of-bounds error
Error class:
‰  Used by the Java run-time system to handle errors occurring in the run-time
environment
‰  Generally beyond the control of user programs
‰  Examples:
oOut of memory errors
oHard disk crash
Tips and Tricks:
List out some of the key exception rules that need to be followed while writing a Java program.
Solution:
You cannot have a catch or finally without a try.
void go() {
Foo f = new Foo();
f.foof();
catch(FooException fe) { }
}
You cannot put code between the try and the catch.
try {
x.doStuff();
}
int y = 50;
} catch(FooException fe) { }
A try must be followed by either a catch or a finally.
try {
x.doStuff();
} finally {
// cleanup
}
A try with only a finally (no catch)must still declarethe exception.
void go() throws FooException {
try {
x.doStuff();
} finally { }
}
Summary
‰  Exceptions come in two flavours: checked and unchecked.
‰  Checked exceptions include all subtypes ofException, excluding classes that extend
RuntimeException.
‰  Checked exceptions are subject to the handle or declare rule; any method that might
throw a checked exception must either declare the exception using throws, or handle
the exception with an appropriate try/catch.
‰  Subtypes of Error or RuntimeException are unchecked.
‰  If you use an optional finally block, it will always be invoked, regardless of whether an
exception in the corresponding try is thrown or not, and regardless of whether a
thrown exception is caught or not

No comments:

Post a Comment