Download presentation
Presentation is loading. Please wait.
Published byFernanda Priddy Modified over 9 years ago
1
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
2
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 – …
3
Exception Handling in Java3 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
4
Exception Example class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(" Pls. print me. "); } Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) Causes the program to terminate
5
Another Example public 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)
6
Exception Handling in Java6 Coding Exceptions To 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
7 Example Output: Division by zero. After catch statement.
8
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"); }
9
Catching Multiple Exceptions Handle 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
10 Exception Handler Exception "thrown" here Exception handler Thrown exception matched against first set of exception handlers If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is discarded
11
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
12
Exception Classes from Standard Packages Predefined exception classes are included in the standard packages that come with Java ◦ For example: IOException NoSuchMethodException FileNotFoundException ◦ Many exception classes must be imported in order to use them import 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.
13
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
14
A Programmer-Defined Exception Class
15
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
16 Runtime Errors
17
17 Catch Runtime Errors
18
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
19 Using the throws Clause Appears after method’s parameter list and before the method’s body Contains a comma-separated list of exceptions Exceptions 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
20 Declaring, Throwing, and Catching Exceptions
21
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
22 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
23
23 Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step
24
24 Sequence of Events for No throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step
25
25 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; InputMismatchExcept ion thrown if input not valid integers
26
26 Call method quotient, which may throw ArithmeticException If we have reached this point, input was valid and denominator was non-zero, so looping can stop Catching 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
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
28 Sequence of Events for finally clause Preceding step try block throw statement unmatched catch matching catch unmatched catch next step finally
29
29 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
30
30 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
31
31 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
32
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
33 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.
34
34 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.