Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 12 Exception Handling and Text IO Part 1

Similar presentations


Presentation on theme: "Chapter 12 Exception Handling and Text IO Part 1"— Presentation transcript:

1 Chapter 12 Exception Handling and Text IO Part 1

2 Exception Handling Exception handling enables a program to deal with exceptional situations and continue its normal execution No exception handling Quotient Run With if-else QuotientWithIf Run With a method QuotientWithMethod Run With try-catch QuotientWithException Run The benefit of using try-catch is that it enables a method to throw an exception to its caller method. Without this capability, a method must handle the exception itself or terminate the program

3 Arithmetic Exception import java.util.Scanner;
public class QuotientWithException { public static int quotient(int number1, int number2) { if (number2 == 0) throw new ArithmeticException("Divisor cannot be zero"); return number1 / number2; } public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); try { int result = quotient(number1, number2); System.out.println(number1 + " / " + number2 + " is " + result); catch (ArithmeticException ex) { System.out.println("Exception: an integer " + "cannot be divided by zero "); System.out.println("Execution continues ...");

4 Exceptions are objects based on the superclass java.lang.Throwable
Exception Types Exceptions are objects based on the superclass java.lang.Throwable

5 Exceptions are objects based on the superclass java.lang.Throwable
Exception Types Exceptions are objects based on the superclass java.lang.Throwable

6 Exception Types Exceptions are objects based on the superclass java.lang.Throwable Built-in exceptions Description Arithmetic Exception Condition has occurred in an arithmetic operation. ArrayIndexOutOfBoundException Array has been accessed with an illegal index, either negative or greater than or equal to the size of the array. ClassNotFoundException Access a class whose definition is not found FileNotFoundException A file is not accessible or does not open. IOException An input-output operation failed or interrupted NullPointerException Referring to the members of a null object. Null represents nothing NumberFormatException A method could not convert a string into a numeric format. StringIndexOutOfBoundsException String class methods to indicate that an index is either negative than the size of the string

7 NullPointer Exception FileNotFound Exception
Exception Examples NullPointer Exception FileNotFound Exception //Java program to demonstrate NullPointerException class NullPointer_Demo {     public static void main(String args[])     {         try {             String a = null; //null value             System.out.println(a.charAt(0));         } catch(NullPointerException e) {             System.out.println("NullPointerException..");         }     } } //Java program to demonstrate FileNotFoundException import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader;  class File_notFound_Demo {        public static void main(String args[])  {             // Following file does not exist             File file = new File("E://file.txt");             FileReader fr = new FileReader(file);         } catch (FileNotFoundException e) {            System.out.println("File does not exist"); Output: NullPointerException.. File does not exist

8 InputMismatchException
Another way to handle similar exceptions is with the help of the InputMismatchException class Example: When executing input.nextInt(), an InputMismatchException occurs if the input entered is not an int and the control is transferred to the catch block The statements in the catch block are now executed InputMismatchExceptionDemo Run

9 Checked & Unchecked Exceptions
Throwable Exception Error All other exceptions RuntimeException subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions

10 Program does not compile if any of these are present
Errors caused by your program and external circumstances These rare internal system errors are thrown by JVM. If one occurs, notify the user and terminate the program Throwable Exception Error Caused by coding faults like bad casting, out-of-bounds array, etc. All other exceptions RuntimeException subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions Program does not compile if any of these are present They happen only after the programs starts running

11 Handling Unchecked Exceptions
In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example: A NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it An IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array These logic errors should be corrected in the program Unchecked exceptions can occur anywhere in the program To avoid cumbersome overuse of try-catch, Java does not mandate you to write code to catch unchecked exceptions

12 Declaring, Throwing and Catching
Java’s exception-handling model is based on three operations: Declaring an exception Throwing an exception Catching an exception Exceptions are declared in and thrown from a method. The caller of that method can catch and handle the exception

13 Declaring Exceptions Examples:
Every method must state the types of checked exceptions it might throw This is known as declaring exceptions Examples: public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

14 Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it This is known as throwing an exception Examples: throw new TheException(); TheException ex = new TheException(); throw ex;

15 Example: Throwing Exception
/** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

16 Catching Exceptions When an exception is thrown, it can be caught and handled in a try-catch block. If no exceptions arise during the execution of the try block, the catch blocks are skipped try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { // handler for exception1 catch (Exception2 exVar2) { // handler for exception2 ... catch (ExceptionN exVarN) { // handler for exceptionN If an exception is not caught in the current method, it is passed to the calling method. The process is repeated until the exception is caught or passed to main()

17 Example: Catching Exceptions
If the exception type is Exception3, it is caught by the catch block for ex3 in method2. statement5 is skipped, and statement6 is executed If the exception type is Exception2, method2 is aborted, control is returned to method1, and the exception is caught by the catch block for ex2 in method1. statement3 is skipped. statement4 is executed If the exception type is Exception1, method1 is aborted, control is returned to main, and the exception is caught by the catch block for ex1 in main. statement1 is skipped. statement2 is executed If the exception type is not caught in method2, method1, or main, the program terminates, and statement1 and statement2 are not executed

18 Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method Example: void p2() throws IOException { if (file closed) throw new IOException("File is closed");} If p1() invokes p2() then we must write code as shown in (a) or (b)

19 Example: Declaring/Throwing/Catching Checked Exception
This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius() in the Circle class defined in Chapter 9 The new setRadius() throws an exception if radius is negative CircleWithException TestCircleWithException Run

20 Rethrowing Exceptions
An exception handler can rethrow the exception if the handler can’t process the exception or simply wants to let its caller be notified of the exception try { // statements } catch(TheException ex) { // perform some operations throw ex; The catch block first catches and processes the exception, and then rethrows it to the caller so that other handlers in the caller get a chance to process ex

21 The finally Block The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or whether an exception is caught if it occurs try { statements; } catch(TheException ex) { handling ex; finally { finalStatements;

22 Trace a Program Execution
animation Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

23 Trace a Program Execution
animation Trace a Program Execution The final block is always executed try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

24 Trace a Program Execution
animation Trace a Program Execution Next statement in the method is executed try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

25 Trace a Program Execution
animation Trace a Program Execution Suppose an exception of type Exception1 is thrown in statement2 try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

26 Trace a Program Execution
animation Trace a Program Execution The exception is handled. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

27 Trace a Program Execution
animation Trace a Program Execution The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

28 Trace a Program Execution
animation Trace a Program Execution The next statement in the method is now executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

29 Trace a Program Execution
animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; statement2 throws an exception of type Exception2.

30 Trace a Program Execution
animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Handling exception

31 Trace a Program Execution
animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Execute the final block

32 Trace a Program Execution
animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Rethrow the exception and control is transferred to the caller


Download ppt "Chapter 12 Exception Handling and Text IO Part 1"

Similar presentations


Ads by Google