ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application...

32
Chapter 12 Exception Handling and Text IO 1

Transcript of ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application...

Page 1: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Chapter 12

Exception Handling and Text IO

1

Page 2: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.1 - Introduction

2

Page 3: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Main mechanism for handling exceptional errors

try { // statements that could raise an exception // or a method call that could raise an exception

} catch (exception_class exception_object) { // statements to handle the exception // or rethrow the exception // specific type (subclass) of exception

} catch (exception_class exception_object) { // ... // more general (superclass) exception type } // end try

3

Page 4: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.2 – Exception Handling Overview

4

Page 5: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<DivisionByZero.java>

5

package inclass.Exceptions; import java.util.Scanner;

public class DivideByZero { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in);

System.out.print("Enter two integers: "); int num = keyboard.nextInt(); int den = keyboard.nextInt();

try { System.out.println("Quotient = " + num / den); } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); } // end try } // end main() } // end DivideByZero Enter two integers: 2 0

/ by zero

Page 6: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.3 – Exception Handling Advantages

6

Page 7: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<DivisionByZeroMethod.java>

7

package inclass.Exceptions; import java.util.Scanner;

public class DivideByZeroMethod {

public static int quotient(int numerator, int denominator) { if (denominator == 0) throw new ArithmeticException("Denominator cannot be 0"); else return numerator / denominator; } // end quotient()

Page 8: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<DivisionByZeroMethod.java>

8

public static void main(String[] args) { Scanner keyboard = new Scanner(System.in);

System.out.print("Enter two integers: "); int num = keyboard.nextInt(); int den = keyboard.nextInt();

try { System.out.println("Quotient = quotient(num, den); } catch (ArithmeticException ae) { System.out.println(ae.getMessage()); } // end try } // end main() } // end DivisionByZeroMethod

Enter two integers: 2 0 Denominator cannot be 0

Page 9: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.4 – Exception Types

9

Page 10: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Exceptions come in two flavors:Checked and Unchecked

10

Object

Throwable

Exception Error

VirtualMachineError

LinkageErrorClassNotFoundException

IOException

RuntimeException

... more

... more

Page 11: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.5 – More on Exception Handling

11

Page 12: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Checked exceptions must be declared

12

method1() {

}

method2() throws Exception {

}

try { invoke method2; } catch (Exception e) { handle exception; }

if (error occurs) { throw new Exception(); }

Declare exception

Throw exceptionCatch exception

Checked exceptions must be either a) caught or b) declared.

In method1(), the exception is caught locally but in method2() it is instead thrown. By throwing the exception you are indicating that some other method higher in the calling order is to handle this error. The compiler however needs to know that there is a possibility for such an error to occur, and so you must indicate so by declaring the exception in the method header.

Page 13: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Exception objects can provide valuable information

13

java.land.Throwable

+getMessage(): String +toString(): String +printStackTrace(): void +getStackTrace(): StackTraceElement[]

Page 14: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<DivisionByZero.java>

14

package inclass.Exceptions;

import java.util.Scanner;

public class DivideByZero { public static void main(String[] args) { // Code omitted ...

try { System.out.println("Quotient = " + num / den); } catch (ArithmeticException ae) { System.out.println("getMessage(): " + ae.getMessage()); System.out.println("toString(): " + ae); System.out.println("printStackTrace(): "); ae.printStackTrace(); } // end try } // end main() } // end DivideByZero

Page 15: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<DivisionByZero.java>

15

Enter two integers: 2 0 getMessage(): / by zero toString(): java.lang.ArithmeticException: / by zero printStackTrace(): java.lang.ArithmeticException: / by zero at inclass.Exceptions.DivideByZero.main(DivideByZero.java:14) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at edu.rice.cs.dynamicjava.symbol.JavaClass$JavaMethod.evaluate(JavaClass.java:362) at edu.rice.cs.dynamicjava.interpreter.ExpressionEvaluator.handleMethodCall(ExpressionEvaluator.java:92) // output omitted

Page 16: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.6 – The finally Clause

16

Page 17: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Do necessary clean-up in the finally block

17

try { // statements that could raise an exception // or a method call that could raise an exception

} catch (exception_class exception_object) { // statements to handle the exception // or rethrow the exception // specific type (subclass) of exception

} catch (exception_class exception_object) { // ... // more general (superclass) exception type } finally { // clean up } // end try

The finally clause is used as a always-execute clause. It executes no matter what happens with the catch clauses. In other words, if an error is caught the finally executes, and if an error does not occur, well the finally still executes.

This provides you the opportunity to do tasks that need to happen no matter what, like releasing resources.

Page 18: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<FinallyDemo.java>

18

package inclass.Exceptions;

import java.io.*;

public class FinallyDemo { public static void main(String[] args) { PrintWriter pw = null; try { pw = new PrintWriter("text.txt"); pw.println("Welcome to java."); } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) pw.close(); } // end try } // end main() } // end FinallyDemo

Page 19: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.7 – When to use Exceptions

19

Page 20: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Follow these guidelines

! Catch error locally ! Handle error in caller

! Use simple if logic with a boolean return when possible

! Use try/catch for exceptional errors

20

Page 21: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.8 – Rethrowing Exceptions

21

Page 22: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

An exception can be rethrown

22

try { statements; } catch (AnException e) { performs tasks before it exits; throw e; } // end try

Page 23: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.9 – Chained Exceptions

23

Page 24: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Exceptions can also be chained

24

try { method(); } catch (AnException e) { // performs tasks before it exits throw new AnException("More info", e); } // end try

method() throws AnException { throw new AnException("Old info"); } // end method()

method() throws an exception with the message "Old info". This object is then caught by the catch clause and a new exception object is thrown. This new object contains the cumulative message from both methods. The message "More info" followed by the message "Old info"

Page 25: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<ChainedExceptionsDemo.java>

25

package inclass.Exceptions;

public class ChainedExceptionsDemo {

public static void main(String[] args) { try { method1(); } catch (Exception e) { e.printStackTrace(); } // end try } // end main()

Page 26: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed< ChainedExceptionsDemo.java >

26

public static void method1() throws Exception { try { method2(); } catch (Exception e) { throw new Exception("New info from method1", e); } // end try } // end method1() public static void method2() throws Exception { throw new Exception("New info from method2"); } // end method2()

} // end ChainedExceptionsDemo

Page 27: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed< ChainedExceptionsDemo.java >

27

java.lang.Exception: New info from method1 at inclass.Exceptions.ChainedExceptionsDemo.method1(ChainedExceptionsDemo.java:16) at inclass.Exceptions.ChainedExceptionsDemo.main(ChainedExceptionsDemo.java:6) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ... more Caused by: java.lang.Exception: New info from method2 at inclass.Exceptions.ChainedExceptionsDemo.method2(ChainedExceptionsDemo.java:21) at inclass.Exceptions.ChainedExceptionsDemo.method1(ChainedExceptionsDemo.java:14) ... 38 more

The error messages are chained in a Stack fashion. The first message generated is at the bottom of the stack and the last one on the top.

Page 28: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

14.10 – Creating Custom Exception Classes

28

Page 29: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

You could always create your own exception class

29

Page 30: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<ArgumentException.java>

30

package testing;

public class ArgumentException extends Exception { private int value; public ArgumentException(int value) { super(value + " is out of range."); this.value = value; } // end ArgumentException() public String toString() { return (value + " is out of range."); } // end toString()

} // end ArgumentException

Page 31: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Application Deconstructed<ArgumentExceptionDemo.java>

31

package testing;

public class ArgumentExceptionDemo { public static void main(String[] args) { try { throw new ArgumentException(-1); } catch (ArgumentException ae) { System.err.println(ae); } // end try } // end main() } // ArgumentExceptionDemo

-1 out of range

Page 32: ch12.Exception Handling and Text IOstornar/courses/notes/cs150/ch12.Exception Han… · Application Deconstructed  7 package inclass.Exceptions; import

Recap: ExceptionsUse a try / catch block to handle exceptions

Pair a try with either a catch or finally block

Trap locally, handle in caller (or above)

Declare or catch checked exceptions

32