230 likes | 416 Views
Exception Handling. Exceptions. Definition Exception types Exception Hierarchy Catching exceptions Throwing exceptions Defining exceptions Common exceptions and errors. What is Exception?. Exceptions are unexpected conditions in a program
E N D
Exception Handling Exception Handling
Exceptions • Definition • Exception types • Exception Hierarchy • Catching exceptions • Throwing exceptions • Defining exceptions • Common exceptions and errors Exception Handling
What is Exception? • Exceptions are unexpected conditions in a program • Exceptions happen at the different levels in a program • They are usually handled at the different levels: • Where they occur • At another level • Exception examples: • Opening file that does not exist • Sending a message to an object that object does not understand Exception Handling
Exceptions in Java • In Java there are two different types of exceptions: • Unchecked exceptions • Runtime exceptions and errors • Checked exceptions • All others exceptions • Exceptions are objects in Java and they are all Throwable type Exception Handling
Exception Hierarchy… Checked, enforced by Compiler Throwable Exception Error RuntimeException Unchecked, thrown by JVM Exception Handling
…Exception Hierarchy • Throwable – top of the exception hierarchy in Java, all exceptions are of this type • Error – represents serious problems in program, that usually cannot be covered from; thrown by the JVM • Exception – superclass for all exceptions including user-defined exceptions • RuntimeException – also thrown by JVM and caused by illegal operations Exception Handling
Unchecked Exceptions • Exceptions that are thrown by the Java Virtual Machine • Cannot be handled at the compilation as compiler does not enforce developers to handle exceptions • These exceptions occur at the runtime • Hard to catch specific unchecked exception as they are not checked by the compiler Exception Handling
Checked Exceptions • Exceptions checked by compiler • Need to be handled in the code as Compiler gives a compile error if they are not handled • Exceptions are thrown by methods that are used in the code • That’s how Compiler recognizes them • What happens when exceptions are caught depends on the exception handling strategy • Exception handling code defines how exceptions are handled Exception Handling
Handling Exceptions in Java • There are two different mechanisms for handling Java exceptions: • Handling exceptions in a method where they are caught • Propagating exceptions to the calling method • Calling method handles the exceptions • Which way you will handle exceptions depend on the overall design of the system Exception Handling
try-catch block • Exceptions are handled in a try-catch block • Checked exceptions can be wrapped in a try-catch block unless they are propagated to a calling method • Exceptions in a catch block can be any exception of Throwable type public void myMethod() { try { //code that throws exception e } catch (Exception e) { //code that handles exception e } } Exception Handling
Catching Multiple Exceptions • It is possible to catch multiple exceptions in a catch block • Order of exceptions is important as more generic exceptions should be handled at the end public void myMethod() { try { //code that throws exception e1 //code that throws exception e2 } catch(MyException e1) { //code that handles exception e1 } catch(Exception e2) { //code that handles exception e2 } } Exception MyException Exception Handling
finally block • Executes always at the end after the last catch block • Commonly used for cleaning up resources (closing files, streams, etc.) public void myMethod() { try { //code that throws exception e1 //code that throws exception e2 } catch (MyException e1) { //code that handles exception e1 } catch (Exception e2) { //code that handles exception e2 } finally { //clean up code, close resources } } Exception Handling
Propagating Exceptions • Can be used instead of try-catch block • Let the calling method handle the exception • Need to declare that method (in which code is defined) throws the exception • Keyword throws is used in method declaration public void myMethod() throws Exception { //code that throws exception e } Exception Handling
Handling Generic Exceptions • If you catch a generic exception that will catch all the exceptions of that particular type • For example, catching Throwable will handle checked and unchecked exceptions public void myMethod() { try { //code } catch (Throwable e) { System.out.println(e.printStackTrace()); } } Exception Handling
Example : Divide by Zero (1) public class DividebyZeroExceptionextends ArithmeticException { public DividebyZeroException() { super( "Attempted to Divide by Zero" ); } public DividebyZeroException( String message ) { super( message ); } } • The above code creates our own Exception Class, which we will use to catch a specific type of error in our program (see next slides) superclass Call to superclass constructor Exception Handling
Example : Divide by Zero (2) import java.text.DecimalFormat; import javax.swing.JOptionPane; public class DividebyZeroTest { // Definition of method quotient. Used to demonstratethrowing an exception // when a divide-by-zero erroris encountered. public static double divide( int numerator, int denominator ) throws DividebyZeroException { if ( denominator == 0 ) throw new DividebyZeroException(); return ( double ) numerator / denominator; } // End of method divide Local method divide( ) which throws our own Exception Exception Handling
Example : Divide by Zero (3) public static void main(String[] args) { String input1, input2, output; int number1, number2; double result; // Initialization input1 = JOptionPane.showInputDialog(null,"Please Enter 1st Number : ","Data Entry",JOptionPane.PLAIN_MESSAGE); input2 = JOptionPane.showInputDialog(null,"Please Enter 2nd Number : ","Data Entry",JOptionPane.PLAIN_MESSAGE); DecimalFormat precision3 = new DecimalFormat( "0.000" ); Exception Handling
Example : Divide by Zero (4) try { number1 = Integer.parseInt( input1 ); number2 = Integer.parseInt( input2 ); result = divide( number1, number2 ); output = "Result : " + precision3.format(result); JOptionPane.showMessageDialog(null,output,"DataOutput“, JOptionPane.INFORMATION_MESSAGE); } Call to method divnums( ) Exception Handling
Example : Divide by Zero (5) catch ( NumberFormatException nfe ) { JOptionPane.showMessageDialog(null,"You must enter 2 integers", “Error Message",JOptionPane.ERROR_MESSAGE ); } catch ( DividebyZeroException dbze ) { JOptionPane.showMessageDialog( null, dbze, “Error Message",JOptionPane.ERROR_MESSAGE ); } System.exit(0); } // End of main } // End of Program dbze.toString() Exception Handling
Some Common Java Exceptions • Unchecked, subclass of RuntimeException: • NullPointerException • Thrown if a message is sent to null object • ArrayIndexOutOfBoundsException • Thrown if an array is accessed by illegal index • Checked: • IOException • Generic class for exceptions produced by input/output operations • NoSuchMethodException • Thrown when a method cannot be found • ClassNotFoundException • Thrown when application tries to load class but definition cannot be found Exception Handling
Throwable Portion of Throwable hierarchy Exception Error Runtime Exception IOException AWTError ThreadDeath OutOf MemoryError ArrayIndexOutOfBoundsException InputMismatchException ClassCastException NullPointerException ArithmeticException Exception Handling
Some Common Java Errors • NoSuchMethodError • Application calls method that no longer exist in the class definition • Usually happens if class definition changes runtime • NoClassDefFoundError • JVM tries to load class and class cannot be found • Usually happens if classpath is not set, or class somehow gets removed from the classpath • ClassFormatError • JVM tries to load class from file that is incorrect • Usually happens if class file is corrupted, or if it isn’t class file Exception Handling
Module Summary • In this module we have discussed: • What exceptions are • What types of exceptions exist in Java • Exceptions hierarchy • Catching exceptions • Throwing exceptions • Defining exceptions • Common exceptions and errors Exception Handling