Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail...
-
Upload
fernanda-priddy -
Category
Documents
-
view
212 -
download
0
Transcript of Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail...
Slides prepared by Rose Williams, Binghamton University
ICS201
Exception Handling
University of Hail
College of Computer Science and Engineering
Department of Computer Science and Software Engineering
What is an Exception?Indication of problem during
execution
Examples
– Divide by zero errors
– Accessing the elements of an array outside its range
– Invalid input
– Opening a non-existent file
– …
Exception Handling in Java 3
Exceptions– a better error handling
Exceptions act similar to method return
flags in that encounter an error.
Exceptions act like global error methods
in that the exception mechanism is built
into Java
Exception Exampleclass DivByZero {public static void main(String args[]) { System.out.println(3/0); System.out.println(" Pls. print me. "); } }Displays this error messageException in thread "main"java.lang.ArithmeticException: / by zeroat DivByZero.main(DivByZero.java:3)
Causes the program to terminate
Another Examplepublic class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha","Beta"};
System.out.println(greek[2]);
}
}
Output:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)
Exception Handling in Java 6
Coding ExceptionsTo handle the exception, you write a “try-
catch” block.
try {… normal program code}catch(Exception e) {… exception handling code}
It prevents the program from automatically terminating
7
Example
Output:Division by zero.
After catch statement.
public class ExceptionExample {
public static void main(String args[]) {
try{
String[] greek = {"Alpha","Beta"};
System.out.println(greek[2]);
}
catch(Exception e)
{
System.out.print ("Index of array out of range");
}
}
}
Catching Multiple ExceptionsHandle multiple possible
exceptions by multiple successive catch blocks
try { // code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
10
Exception Handler
Exception "thrown"
here
Exception handler
Exception handler
Thrown exception matched against first set of exception
handlers
Thrown exception matched against first set of exception
handlers
If it fails to match, it is matched against next set of handlers, etc.
If it fails to match, it is matched against next set of handlers, etc.
If exception matches none of handlers, program is discarded
If exception matches none of handlers, program is discarded
Exception Classes
There are two kinds of exceptions in Java
Predefined exception classes in the Java
libraries
New exception classes can be defined like any other
class
Exception Classes from Standard Packages
Predefined exception classes are included in the standard packages that come with Java◦ For example:IOExceptionNoSuchMethodExceptionFileNotFoundException
◦ Many exception classes must be imported in order to use themimport java.io.IOException;
All predefined exception classes have the following properties:◦ There is a constructor that takes a single argument of
type String◦ The class has an accessor method getMessage that can
recover the string given as an argument to the constructor when the exception object was created.
Exception Classes from Standard Packages
The predefined exception class Exception is the root class for all exceptions
◦ Every exception class is a derived class of the class Exception
◦ Although the Exception class can be used directly in a class or program, it is most often used to define a derived class
◦ The class Exception is in the java.lang package, and so requires no import statement
9-13
A Programmer-Defined Exception Class
15
Types of error:
1. Syntax errors: the rules of the language have
not been followed (detected by the compiler).
2. Runtime errors occur while the program is
running (detects an operation that is
impossible to carry out).
3. Logic errors occur when a program doesn't
perform the way it was intended to.
16
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.
17
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 e) { 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.
18
Throwing Exceptions
When the program detects an error, the program can create an instance of an exception type and throw it. This is known as throwing an exception.
19
Using the throws ClauseAppears after method’s parameter list and before
the method’s bodyContains a comma-separated list of exceptionsExceptions can be thrown by statements in
method’s body of by methods called in method’s body
Exceptions can be of types listed in throws clause or subclasses
20
Declaring, 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
declare exception
21
Declaring Exceptions
Every method state the types of checked exceptions it might throw.
public void myMethod() throws IOException
public void myMethod() throws IOException, OtherException
22
Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
23
Sequence of Events for throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
24
Sequence of Events for No throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
25
1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java
2 // An exception-handling example that checks for divide-by-zero.
3 import java.util.InputMismatchException;
4 import java.util.Scanner;
5
6 public class DivideByZeroWithExceptionHandling
7 {
8 // demonstrates throwing an exception when a divide-by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14
15 public static void main( String args[] )
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19
20 do
21 {
22 try // read two numbers and calculate quotient
23 {
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28
throws clause specifies that method quotient may
throw an ArithmeticException
Repetition statement loops until try block completes
successfully
try block attempts to read input and perform division
Retrieve input; InputMismatchException thrown if input not valid
integers
26
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,
31 denominator, result );
32 continueLoop = false; // input successful; end looping
33 } // end try
34 catch ( InputMismatchException inputMismatchException )
35 {
36 System.err.printf( "\nException: %s\n",
37 inputMismatchException );
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 "You must enter integers. Please try again.\n" );
41 } // end catch
42 catch ( ArithmeticException arithmeticException )
43 {
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println(
46 "Zero is an invalid denominator. Please try again.\n" );
47 } // end catch
48 } while ( continueLoop ); // end do...while
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling
Call method quotient, which may throw
ArithmeticExceptionIf we have reached this point,
input was valid and denominator was non-zero,
so looping can stopCatching InputMismatchException (user has entered non-integer input)
Read invalid input but do nothing with it
Exception parameters
Notify user of error made
Catching ArithmeticException (user has entered zero for denominator)
If line 32 was never successfully reached, loop continues and user can try again
27
The finally Clause
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code.
28
Sequence of Events for finally clause
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
finally
29
Trace a Program Execution
try { statements;}catch(TheException ex) {
handling ex; }finally { finalStatements; }
Next statement;
Suppose no exceptions in the
statements
30
Trace a Program Execution
try { statements;}catch(TheException ex) {
handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed
31
Trace a Program Execution
try { statements;}catch(TheException ex) {
handling ex; }finally { finalStatements; }
Next statement;
Next statement in the method is
executed
32
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
33
Trace a Program Execution
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The exception is handled.
34
Trace a Program Execution
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed.