28
Chapter 13 Exception Handling Claiming Exceptions Throwing Exceptions Catching Exceptions Rethrowing Exceptions The finally Clause Cautions When Using Exceptions Exception Types

Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions The finally Clause F Cautions

Embed Size (px)

Citation preview

Page 1: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Chapter 13 Exception Handling

Claiming Exceptions Throwing Exceptions Catching Exceptions Rethrowing Exceptions The finally Clause Cautions When Using Exceptions Exception Types

Page 2: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Mistakes happenNo matter how well designed a program is, there is

always the chance that some kind of error will arise

during its execution. Attempting to divide by 0; Attempting to read from a file which does not exist; Referring to non-existing item in array; etc.An exceptionexception is an event that occurs during theexecution of a program that disrupt its normalcourse.

Page 3: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Main idea

Java was designed with the understanding that

errors occur, that unexpected events happened

and the programmer should always be prepared

for the worst. The preferred way of handling such conditions

is to use exception handling, an approach that

separates a program’s normal code from its

error-handling code.

Page 4: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example: Open file and read contents

ask the user for the name of a file open the file read the contents do something with the contents close the file

Does the file exist?

Can we open the file?

Can we read data from the file?

Page 5: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Exceptions Exception is a useful programming construct because

the location where an error is detected is usually not the

place where the appropriate solution is known.

Constructors are not permitted to return a null value,

furthermore there might be multiple reasons for a failure. Does a null value returned by a file open operation

mean the file does not exist, or that it exists but cannot

be read? Finally, what if a null value is perfectly

legal?

Page 6: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Claiming, Throwing, and Catching Exceptions

method1() { try { invoke method2; } catch (Exception ex) { Process exception; } }

method2() throws Exception { if (an error occurs) { throw new Exception(); } }

catch exception throw exception

claim exception

Page 7: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example 1a: Division When a statement causes error, the method containing

the statement creates exception object and passes it to the

system.

Class Test { public static main(String args[]) { int d, a; d = 0; a = 1/d; }}

Output:java.lang.ArithmeticException: / by zero

at samples.Test.main(Test.java:5)

Page 8: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Exception handling After a method throws an exception, the Java runtime

system begins the process of finding the code to handle the error.

The code that handles the error is called the exception handler; it is found by searching backward through a chain of method calls, starting from the current method.

The process of finding a handler is called catching an exception.

If no handler is found, the program terminates.

Page 9: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example 1b: Divisionint d, a;d = 0;try { a = 1/d; System.out.println(“It will not be printed”);}catch (ArithmeticException except) { System.out.println(“Division by zero!”);}System.out.println(“After catch statement.”);

Output:Division by zero!After catch statement.

Page 10: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example 1c: Divisionint d, a;d = 0;try { // The method now claims an exception and throws it if the divisor is zero. if(d==0) throw new RuntimeException(); a = 1/d;}catch (RuntimeException except) { System.out.println(except);}System.out.println(“After catch statement.”);

Output:java.lang.RunTimeExceptionAfter catch statement.

Page 11: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example 2: String to integerString str1=“123”, str2=“xwz”;try { int i1 = Integer.parseInt(str1); System.out.println(“The 1st int value ” + i1); int i2 = Integer.parseInt(str2); System.out.println(“The 2nd int value ” + i2);}catch (NumberFormatException exc) { System.out.println(exc);}…

OutputThe 1st int value is 123java.lang.NumberFormatException: For input string: "xwz"

Page 12: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Exceptions handling

1. Claiming Exceptions

2. Throwing Exceptions

3. Catching Exceptions

Page 13: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

1. Claiming Exceptions

To claim an exception in a method, use the throwsthrowskeyword.

modifiers MethodName(list of params) throws

Exception_1, Exception_2, ..., Exception_N

Example:public void myMethod() throws IOException{ ...}

Page 14: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Claiming Exception Example

// The method divide(k,m) returns result of division,

// n = k/m; public int divide(int k, int m) throwsthrows

RuntimeExceptionRuntimeException

{

...

}

Page 15: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

2. Throwing Exceptions

In the method that has claimed the exception, you

can throw an object of the exception if the exception

arises.

throw new TheException();

TheException e = new TheException();

throw e;

Page 16: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Throwing Exceptions Examplepublic int divide(int k, int m) throws RunTimeException{ if(m == 0)

{ throw new RuntimeException(”Divisor can’t be zero");throw new RuntimeException(”Divisor can’t be zero"); } return k/m;}

Page 17: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

3. Catching Exceptions

try { statements;}catch(Exception1 e){ catch(Exception1 e){ handler for exception1; handler for exception1; }}catch (Exception2 e) { catch (Exception2 e) { handler for exception2; handler for exception2; }}......catch (ExceptionN e){ catch (ExceptionN e){ handler for exceptionN; handler for exceptionN; }}

Page 18: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Catching Exceptions Example

try { int n = divide(k,m); }catch(RuntimeException e){ System.out.println(“Error! Division by 0.”); }

Page 19: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Methods of Exception object

public String getMessage() // Returns detailed message of the object

public String toString()

// Returns short description of the object

public void printStackTrace()

// Print trace information: class name, method name, file name, and line number.

java.lang.ArithmeticException: /by zero

at MyClass,divide(MyClass.java:5)

Page 20: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Open File Example, cont.

trytry {

File fd = new File(filename);

processFile(fd);

fd.close()

}

catch (FileNotFound e) {catch (FileNotFound e) {

System.out.println(“Cannot find file”+e);System.out.println(“Cannot find file”+e);

e.printStackTrace(); e.printStackTrace();

}}

catch (FileOpenFailed e) {catch (FileOpenFailed e) {

System.out.println(“Cannot open file”+e);System.out.println(“Cannot open file”+e);

e.printStackTrace(); e.printStackTrace();

}}

Page 21: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Claiming, Throwing, and Catching Exceptions

method1() { try { invoke method2; } catch (Exception ex) { Process exception; } }

method2() throws Exception { if (an error occurs) { throw new Exception(); } }

catch exception throw exception

claim exception

Page 22: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

ReRethrowing Exceptions

try { statements;}catch(TheException e){ perform operations before exits; throw e;throw e;}

Page 23: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Catching Exceptions

main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } }

method1 { ... try { ... invoke method2; statement2; } catch (Exception2 ex2) { Process ex2; } }

method2 { ... try { ... invoke method3; statement3; } catch (Exception3 ex3) { Process ex3; } }

Page 24: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

The finally Clause You may want some code to be executed regardless of

whether an exception occurs or is caught. Java has a finally clause that can accomplish this objective.

try{ statements;}catch(TheException1 e){ handling e; }catch(TheException2 e){ handling e; }finally{ finalStatements; }

Page 25: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

The finally Clause If no exception arises in the try block, finalStatement is

executed. If one of the statements causes an exception in try block that

is caught in a catch clause, the other statements in try block are skipped, the catch clause is executed, and the finally clause is executed.

* If the catch clause does not rethrow an exception, the next statement is executed.

* If it does, the exception is passed to the caller of the method. If one of the statements causes an exception is not caught in

any catch clause, the other statements in the try block are skipped, the finally clause is executed, and the exception is passed to the caller of this method.

Page 26: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Example: finallySuppose that statement2 causes an exception ex2:

try{ statement1; statement2; statement3;}catch(TheException1 ex1) { handling ex1; }catch(TheException2 ex2) { handling ex2; }finally { finalStatement; }statement 4;

Output: statement1; finalStatement;statement4;

Page 27: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Cautions When Using Exceptions Exception handling separates error-handling code from

normal programming tasks, thus making programs easier to read and to modify.

Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

Page 28: Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions

Exceptions and Exception Types