Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.

Similar presentations

Presentation on theme: "Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions."— Presentation transcript:

1 Exception Handling1

2 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions  Common exceptions and errors

3 Exception Handling3 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

4 Exception Handling4 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

5 Exception Handling5 Exception Hierarchy… Throwable ExceptionError RuntimeException Unchecked, thrown by JVM Checked, enforced by Compiler

6 Exception Handling6 …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

7 Exception Handling7 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

8 Exception Handling8 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

9 Exception Handling9 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

10 Exception Handling10 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 }

11 Exception Handling11 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

12 Exception Handling12 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 }

13 Exception Handling13 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 }

14 Exception Handling14 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()); }

15 Exception Handling15 Example : Divide by Zero (1) public class DividebyZeroException extends 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) Call to superclass constructor superclass

16 Exception Handling16 Example : Divide by Zero (2) import java.text.DecimalFormat; import javax.swing.JOptionPane; public class DividebyZeroTest { // Definition of method quotient. Used to demonstrate throwing an exception // when a divide-by-zero error is 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

17 Exception Handling17 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" );

18 Exception Handling18 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,"Data Output“, JOptionPane.INFORMATION_MESSAGE); } Call to method divnums( )

19 Exception Handling19 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()

20 Exception Handling20 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

21 Exception Handling21 Throwable ExceptionError IOException ArrayIndexOutOfBoundsExceptionInputMismatchException NullPointerException Runtime Exception AWTErrorThreadDeath ClassCastException OutOf MemoryError ArithmeticException Portion of Throwable hierarchy

22 Exception Handling22 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

23 Exception Handling23 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

Download ppt "Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions."

Similar presentations

Ads by Google