340 likes | 411 Views
University of Hail College of Computer Science and Engineering. Department of Computer Science and Software Engineering. ICS201 Exception Handling. What is an Exception?. Indication of problem during execution Examples – Divide by zero errors
E N D
University of Hail College of Computer Science and Engineering Department of Computer Science and Software Engineering ICS201 Exception Handling
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 – …
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 Handling in Java
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
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)
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 Exception Handling in Java
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 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 }
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 Exception Handler Exception "thrown" here Exception handler Exception handler
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: 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.
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
Types of error: • Syntaxerrors: the rules of the language have not been followed (detected by the compiler). • Runtime errorsoccur while the program is running (detects an operation that is impossible to carry out). • Logic errors occur when a program doesn't perform the way it was intended to.
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.
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
Declaring Exceptions Every method state the types of checked exceptions it might throw. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException
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"); }
Sequence of Events for throw Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch next step
Sequence of Events for No throw Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch next step
try block attempts to read input and perform division throws clause specifies that method quotient may throw an ArithmeticException Repetition statement loops until try block completes successfully Retrieve input; InputMismatchException thrown if input not valid integers
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) Catching ArithmeticException (user has entered zero for denominator) If line 32 was never successfully reached, loop continues and user can try again Exception parameters Read invalid input but do nothing with it Notify user of error made
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.
Sequence of Events for finally clause Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch finally next step
Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;
Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
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
Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.
Trace a Program Execution The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;