35
Exception handling

Comp102 lec 10

Embed Size (px)

Citation preview

Page 1: Comp102   lec 10

Exception handling

Page 2: Comp102   lec 10

Introduction

Programming errors are unavoidable, even for experienced programmers. Have three categories of

errors: syntax errors, runtime errors, and logic errors Syntax errors arise because the rules of the language

have not been followed detected by the compiler.

Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out

Logic errors occur when the program doesn’t perform the way it is intended to

Page 3: Comp102   lec 10

Exception handling

Exception handling deals with runtime errors. Runtime errors cause exceptions: events that

occur during the execution of a program and disrupts the normal flow of control.

A program that does not provide code to handle exceptions may terminate abnormally, causing serious problem

Page 4: Comp102   lec 10

The Basics of Java Exception Handling

Exception handling Method detects error which it cannot deal with

Throws an exception Exception handler

Code to catch exception and handle it Exception only caught if handler exists

If exception not caught, block terminates

Page 5: Comp102   lec 10

The Basics of Java Exception Handling Format

Enclose code that may have an error in try block

Follow with one or more catch blocks Each catch block has an exception

handler If exception occurs and matches

parameter in catch block Code in catch block executed

If no exception thrown Exception handling code skipped Control resumes after catch blocks

try{ code that may throw exceptions}catch (ExceptionType ref) { exception handling code}

Page 6: Comp102   lec 10

The Basics of Java Exception Handling Termination model of exception handling

throw point Place where exception occurred Control cannot return to throw point

Block which threw exception expires Possible to give information to exception handler

Page 7: Comp102   lec 10

Java provides programmers with the capability to handle runtime errors. With this capability, referred to as exception handling, so you can develop robust programs for mission-critical computing.

The following program terminates abnormally because the divisor is 0, which causes a numerical error. Note there is no code to explicitly to explicitly handle the exception

public class Test{ public static void main(String [] args) { System.out.println(3/0); // Throws ArithmeticException

} }

Page 8: Comp102   lec 10

To handle the divisor by zero error, use a new construct called the try-catch block to enable the program to catch the error and continue to execute.

public class test1{ public static void main(String [] args)

{ try

{ System.out.println(3/0); } catch (Exception ex)

{ System.out.println("Error:" +

ex.getMessage());}

System.out.println("Execution continues"); }}

Page 9: Comp102   lec 10

Exceptions and Exception Types

Various reasons for runtime error:

The user enters an invalid input – the program may try to open a file that does not exist

the network connection may hang up

the program may try to access an out of bound s array element

When an exception occurs, however, the program may terminate if no handler can be used to deal with it.

Page 10: Comp102   lec 10

Catching Exceptions

try { statements; //Statement that may throw //exceptions}catch (Exception1 ex) { handler for exception1 }catch (Exception2 ex) { handler for exception2 }

...

catch (ExceptionN ex) { handler for exceptionN }

If no exceptions arise during the execution of the try clause,the catch clauses are skipped.

Page 11: Comp102   lec 10

Runtime Errors

import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); } }

If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated.

Terminated.

1 2 3 4 5 6 7 8 9 10 11 12 13

Page 12: Comp102   lec 10

Catch Runtime Errors

import java.util.*; public class HandleExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);

boolean continueInput = true;

do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextLine(); // discard input } } while (continueInput); } }

If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 13

Page 13: Comp102   lec 10

Exception Classes

Page 14: Comp102   lec 10

System Errors

System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Page 15: Comp102   lec 10

Exceptions

Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Page 16: Comp102   lec 10

Runtime Exceptions

RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

Page 17: Comp102   lec 10

Classifying Java Exceptions Unchecked Exceptions

It is not required that these types of exceptions be caught or declared on a method. Runtime exceptions can be

generated by methods or by the JVM itself.

Errors are generated from deep within the JVM, and often indicate a truly fatal state.

Runtime exceptions are a source of major controversy!

Checked ExceptionsMust either be caught by a method or declared in its signature. Placing exceptions in the

method signature harkens back to a major concern for Goodenough.

This requirement is viewed with derision in the hardcore C++ community.

A common technique for simplifying checked exceptions is subsumption.

Page 18: Comp102   lec 10

Keywords for Java Exceptions throws

Describes the exceptions which can be raised by a method.

throwRaises an exception to the first available handler in the call stack, unwinding the stack along the way.

tryMarks the start of a block associated with a set of exception handlers.

catchIf the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption.

finallyAlways called when the try block concludes, and after any necessary catch handler is complete.

Page 19: Comp102   lec 10

Canonical Examplepublic void foo() {

try { /* marks the start of a try-catch block */

int a[] = new int[2];

a[4] = 1; /* causes a runtime exception due to the index */

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("exception: " + e.getMessage());

e.printStackTrace();

}

}

/* This code also compiles, but throws an exception at runtime! It

* is both less obvious and more common (an off-by-one-error). */

public int[] bar() {

int a[] = new int[2];

for (int x = 0; x <= 2; x++) { a[x] = 0; }

return a;

}

Page 20: Comp102   lec 10

blocks

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Page 21: Comp102   lec 10

Trace a Program Execution

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

Suppose no exceptions in the statements

Page 22: Comp102   lec 10

Trace a Program Execution

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed

Page 23: Comp102   lec 10

Trace a Program Execution

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;

Next statement in the method is executed

Page 24: Comp102   lec 10

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

Suppose an exception of type Exception1 is thrown in statement2

Page 25: Comp102   lec 10

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The exception is handled.

Page 26: Comp102   lec 10

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed.

Page 27: Comp102   lec 10

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The next statement in the method is now executed.

Page 28: Comp102   lec 10

Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;

statement2 throws an exception of type Exception2.

Page 29: Comp102   lec 10

Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;

Handling exception

Page 30: Comp102   lec 10

Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;

Execute the final block

Page 31: Comp102   lec 10

Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;

Rethrow the exception and control is transferred to the caller

Page 32: Comp102   lec 10

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 33: Comp102   lec 10

When to Throw Exceptions

An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.

Page 34: Comp102   lec 10

When to Use Exceptions

When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code

try {

System.out.println(refVar.toString());

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}

Page 35: Comp102   lec 10

When to Use Exceptions

is better to be replaced by

if (refVar != null)

System.out.println(refVar.toString());

else

System.out.println("refVar is null");