1 / 34

ICS201 Exception Handling

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

hank
Download Presentation

ICS201 Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. University of Hail College of Computer Science and Engineering Department of Computer Science and Software Engineering ICS201 Exception Handling

  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. 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

  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. 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

  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. 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

  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

  14. A Programmer-Defined Exception Class

  15. 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.

  16. Runtime Errors

  17. Catch Runtime Errors

  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 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. Declaring, Throwing, and Catching Exceptions

  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 Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch next step

  24. Sequence of Events for No throw Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch next step

  25. 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

  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) 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

  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 Precedingstep try blockthrow statement unmatched catch matching catch unmatched catch finally next step

  29. Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  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 The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

More Related