Exception handling

Download Report

Transcript Exception handling

EXCEPTION HANDLING
Byju Veedu
http://download.oracle.com/javase/tutorial/ess
ential/exceptions/index.html
What is an exception?
• An event that occurs during the execution of a program
that interrupts the normal flow of execution.
• Errors are serious conditions from which we better avoids
recovery of the program.
• Exceptions are mid-error conditions that rather than
terminating the program ,we can handle such exceptions
and continue program execution
Exception hierarchy
Java.lang.Object
Java.lang.Throwable
Java.lang.Error
Java.lang.Exception
Java.lang.IOException
Java.lang.RuntimeException
Runtime exceptions
• Exceptions that can be thrown during the normal
operation of JVM
• Compiler doesn’t force you to catch or specify runtime
exceptions although you can.
• Eg:
NullPointerException
ClassCastException
ArithmeticException
Checked Exceptions
• Checked exceptions are not runtime exceptions and are
checked by the compiler. Compiler checks that these
exceptions are caught or specified.
• Eg:
IOException
SQLException
ClassNotFoundException
Example
public class ExceptionDemo {
public static void main(String[] args) {
int x,y;
try {
x = 0;
y = 10;
int div = y / x;
}
catch (ArithmeticException e) {
System.out.println("Exception :"+e.getMessage());
}catch (Exception e) {
e.printStackTrace();
}
}
}
Exception handling
• Try
Use the try statement with the code that might throw exception
• Catch
Specify the exception to catch and the code to execute if the specified
exception is thrown.
• Finally
Used to define a block of code that we always want to execute, regardless of
whether an exception is thrown or not.
• Throw
Used for throwing exceptions .(Usually a user defined exception).
• Throws
Lists the type of exceptions a method can throw ,so that the callers of the
method can guard themselves against those exceptions.
Advantages
• Separating Error-Handling Code from "Regular" Code
• Propagating Errors Up the Call Stack
• Grouping and Differentiating Error Types
Best practices
• Catch runtime exceptions only if necessary. Otherwise
throw it out and catch at the end of execution and log it.
• Create your own exception class to catch more details of
an exception and use it.
• Choose a proper exception propagation model that suites
your program execution.
• Don’t leave an empty catch block. This suppresses the
exception and user won’t know any exception occurred or
not. Use a proper logging mechanism to log the
exception.
Hands-on
• Use of try-catch blocks
• Handling checked exceptions
• Use of throw and throws
• Creating user defined exception classes
• Example of error
References
• http://download.oracle.com/javase/tutorial/essential/excep
tions/index.html
• http://www.artima.com/designtechniques/exceptions.html