Java Exceptions PDF
Document Details
Uploaded by YouthfulTsavorite7659
Vietnam-France University
Tags
Summary
This document provides an overview of Java exceptions and how to handle them. It includes examples of common exception types and how to use try-catch and finally blocks to deal with errors during program execution. The document also offers strategies for tracing exceptions.
Full Transcript
Object-Oriented Programming Exceptions Outline Concept of exception Throwing and catching exceptions Rethrowing exceptions Tracing exceptions 2 What is Exception? Exception is an indication of proble...
Object-Oriented Programming Exceptions Outline Concept of exception Throwing and catching exceptions Rethrowing exceptions Tracing exceptions 2 What is Exception? Exception is an indication of problem that arises during the execution of a program Exception happens in case of: § Designing errors § Programming errors § Data errors § System errors §... 3 Example: Open File import java.io.PrintWriter; import java.io.File; Open file to write class FileWriter { public static void write(String fileName, String s) { File file = new File(fileName); PrintWriter out = new PrintWriter(file); out.println(s); out.close(); } } Compile-time error 4 Example: Invalid Input import java.util.*; public class TestException { public static void main (String args[]) { What happens if input is not Scanner scanner = new Scanner(System.in); a valid integer? System.out.print("Numerator: "); int numerator = scanner.nextInt(); System.out.print("Denominator: "); int denominator = scanner.nextInt(); int result = numerator/denominator; System.out.printf("\nResult: %d / %d = %d\n", numerator, denominator, result ); } } Runtime error by invalid integer input “abc” 5 Example: Divide by Zero import java.util.*; public class TestException { public static void main (String args[]) { Scanner scanner = new Scanner(System.in); System.out.print("Numerator: "); int numerator = scanner.nextInt(); What happens if denominator System.out.print("Denominator: "); is zero? int denominator = scanner.nextInt(); int result = numerator/denominator; System.out.printf("\nResult: %d / %d = %d\n", numerator, denominator, result ); } } Runtime error by dividing zero 6 Throwing exceptions Exception is thrown to an object that contains information about the error throws clause – specifies types of exceptions a method may throw Thrown exceptions can be: in method’s body, or from method’s header 7 Throwing exceptions class Fraction { Declare what type of private int numerator, denominator; exceptions the method might throw public Fraction (int n, int d) throws ArithmeticException { if (d==0) throw new ArithmeticException(); An ArithmeticException object is numerator = n; denominator = d; created and thrown in method’s } body } public class TestException2 { public static void main(String [] args) { Fraction f = new Fraction (2,0); } } 8 Throw Point Throw point is the initial point at which the exception occurs import java.util.*; public class TestException { public static void main (String args[]) { Scanner scanner = new Scanner(System.in); System.out.print("Numerator: "); int numerator = scanner.nextInt(); Throw Point … } } 9 Catching exceptions try { Syntax: // throw an exception } catch (TypeOfException e) { // exception-handling statements } Separate the code that describes what you want to do (program logic) from the code that is executed when things go wrong (error handling) § try block – program logic: encloses code that might throw an exception and the code that should not be executed if an exception occurs § catch block – error handling: catches and handles an exception 10 Catching exceptions A catch block can catch: – Exception of the declared type: catch (IOException e) { // catch exceptions of type IOException } – Exception of a subclass of the declared type: catch (IOException e) { // catch exceptions of type FileNotFoundException // or EOFException… } Uncaught exception: an exception that occurs when there is no catch blocks matches 11 How try and catch work? 12 try { the catch block 1 1. No errors int n = scanner.nextInt(); is skipped System.out.print("Ok"); } catch (Exception e) { System.out.println("Error! "); } % java Tester 2 System.out.println("Done."); 10 Ok Done. 2. The error try { the rest of the try block is caught 1 int n = scanner.nextInt(); is skipped and handled System.out.print("Ok"); } catch (Exception e) { 2 System.out.println("Error! "); } % java Tester 3 System.out.println("Done."); abc Error! Done. 13 3. The error cannot be caught try { 1 int n = scanner.nextInt(); System.out.print("Ok"); the rest of the method, } is skipped catch (ArithmeticException e) { System.out.println("Error! "); } System.out.println("Done."); } // end of method control gets out of the method 14 finally block Optional in a try statement try { Placed after last catch block … } Always executed, except when catch(Exception1 e1) { application exits from try block by … method “System.exit()” } catch(Exception2 e2) { Often contains resource-release code, … such as file closing } finally { … } 15 How finally works? 16 Example: finally block public class TestFinallyBlock { public static void main(String args[]) { try { String a = null; System.out.println("a is " + a.toLowerCase()); } catch (NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code"); } } 17 Java Exception Hierarchy 18 Handling exceptions The goal is to resolve exceptions so that the program can continue or terminate gracefully Handling exception enables programmers to create programs that are more robust and fault-tolerant 19 Exception handling methods Three choices to put to a method: § catch and handle § try and catch blocks § pass it on to the method’s caller § thrown exceptions § catch, handle, then pass it on § re-thrown exceptions 20 Rethrowing exceptions Exceptions can be re-thrown when a catch block decides that: – it cannot process the exception, or – it can process the exception only partially Example: try {... } catch (Exception e) { System.out.println(e.getMessage()); throw e; } 21 Tracing exceptions Can use printStackTrace() to trace back to the point where an exception was issued public class TestFinallyBlock { public static void main(String args[]) { try { String a = null; System.out.println("a is " + a.toLowerCase()); } catch (NullPointerException e) { e.printStackTrace(); } } } 22 23