1 / 24

Exception Handling

Exception Handling. Yaodong Bi bi@cs.uofs.edu. Exception Handling. Java exception handling Try blocks Throwing and re-throwing an exception Catching an exception Throws clause Exceptions in constructors and finalizers Exception and inheritance The finally block

eljah
Télécharger la présentation

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. Exception Handling Yaodong Bi bi@cs.uofs.edu

  2. Exception Handling • Java exception handling • Try blocks • Throwing and re-throwing an exception • Catching an exception • Throws clause • Exceptions in constructors and finalizers • Exception and inheritance • The finally block • PrintStackTrace() and getMessage()

  3. Java Exception Handling • To process only exceptional situations where a method is unable to complete the task for reasons it cannot control • To process exceptions from program components that are not geared to handling those exceptions directly • To process exceptions from components such as libraries and classes that are likely to be widely used and where those components cannot handle their own exceptions

  4. Java Exception Handling • When an exception does not occur, little or no overhead is imposed by the presence of exception handling code. • When exceptions occur, they do incur execution-time overhead • Use Java’s standardized exception handling to improve program clarity and fault tolerance

  5. Exception Handling Basics • When a block of code (ex., a method) detects an error it cannot handle, it throws an exception • The programmer encloses in a try block the code that may throw an exception. • The try block is immediately followed by zero or more catch blocks to catch the exception(s) • Each catch block specifies the type of exception it can catch and contains an exception handler • An optional finally block (mandatory when no catch clause provided) will be executed regardless of whether or not there is an exception.

  6. Exception Handling Basic • A method can use a throws clause to specify what exceptions it may throw • Java employs the termination model of exception handling. • Once an exception is thrown, the block in which the exception is thrown terminates and control cannot return to the throw point

  7. Ex. 1: Divide By Zero public class ExceptionHandling { public static int quotient(int numerator, int denominator) throws DivideByZeroException { if (denominator == 0) throw new DivideByZeroException(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (DivideByZeroException e) { System.err.println(e.toString()); }

  8. Ex. 1: Divide By Zero finally { System.out.println("Finally Block"); } } } // the following is saved in a separate file public class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super("Divide by Zero"); } public DivideByZeroException(String s) { super(s); } }

  9. Try blocks try { // code that may throw exceptions } catch (ExceptionType ref) { // exception handler } • A try block can be followed by zero or more catch blocks • If the try block executes with no exception thrown, all the exception handlers are skipped and control resumes with the first statement after the last exception handler • If a finally block follows the last catch block, it will be executed regardless of whether or not an exception is thrown

  10. Throwing Exceptions • The throw statement makes an exception to occur – throwing an exception • throw new DivideByZeroException(); • A throw statement must throw an object of any class derived from class Throwable • When an exception is thrown, control exits the current try block and proceeds to an appropriate catch handler • When toString() is invoked on any Throwable object, it returns the String that was supplied to the constructor public class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super("Divide by Zero"); // return by toString() }

  11. Catching Exceptions • Each catch block starts with the keyword catch followed by parentheses containing a class name (type of exception) • The Exception object caught can be referred through the parameter catch (ExceptionType ref) { // using ref to refer to the exception object } • It is possible that several handlers provide an acceptable match to the type of the exception, the first exception handler that matches the exception type is executed.

  12. Catching Exceptions • Each catch block defines a distinct scope • An exception handler cannot access objects defined in other handlers • Objects defined in a try block cannot be accessed in its exception handlers try { int tryX= 100; … } catch (ExceptionType1 ref) { int catch1Y = 200; // tryX is NOT accessible here } catch (ExceptionType2 ref) { // both tryX and catch1Y are NOT accessible here }

  13. Catching Exceptions • Exceptions thrown from a handler cannot be caught by the catch blocks of the current try-catch structure 1 try { 2 try { throw new ExcType1(); } 3 catch (ExcType1 ref) 4 { 5 throw new ExcType2(); 6 } 7 catch (ExcType2 ref) 8 { 9 // this will NOT catch the ExcType2 thrown from line 5 10 } 11 catch (ExcType2 ref) 12 { 13 // catch the ExcType2 exception thrown from line 5 14 }

  14. Re-throwing Exceptions • When a exception handler cannot or does not want to handle the caught exception completely, it can re-throw the exception using the throw statement. • Such a re-thrown exception is handled by the enclosing try-catch block 1 try { 2 try { throw new ExcType1(); } 3 catch (ExcType1 ref) 4 { 5 throw ref; 6 } 7 catch (ExcType1 ref) 8 { 9 // catch the ExcType1 exception thrown from line 5 10 }

  15. Throws Clause • A throws clause lists the exceptions that can be thrown by a method void foo() throws ExceptionA, ExceptionB ExceptionA { // may throw the above three exceptions } • All exceptions must be handled exception Error and RuntimeException • If a method does not handle exceptions that may be thrown from its body, it must use the throws clause for the caller to handle the exceptions public void addCourse(String cid, String ttl) throws SQLException { … st.executeUpdate(sql); // may throw SQLException }

  16. Object Error Exception RuntimeException Throwable AWTError LinkageError ClassNotFoundException NoSuchMethodException ArithmeticException ArrayStoreException Java Exception Hierarchy Must be handled

  17. Java Exception Hierarchy • You can throw only objects that derive from the Throwable class. • Errors: • When a "hard" failure in the virtual machine occurs, the virtual machine throws an Error. • Typical Java programs should not catch Errors and it's unlikely that typical Java programs will ever throw Errors either. • Exceptions: • Most programs throw and catch objects that derive from the Exception class. • Exception has a special subclass RuntimeException which is not required to be handled

  18. Runtime Exceptions • The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). • An example of a runtime exception is NullPointerException. • The Java packages define several RuntimeException classes. You can catch these exceptions just like other exceptions. • A method is not required to specify that it throws RuntimeExceptions. • The cost of checking for all RuntimeExceptions often outweighs the benefit of catching it. • the compiler allows RuntimeExceptions to go uncaught and unspecified.

  19. Exception and Inheritance • If a catch is written to catch exception objects of a superclass type, it can also catch all objects of subclasses of that superclass • catch (Exception e) { } would catch almost all exceptions • This also allows for polymorphic processing of related exceptions • It is a syntax error if a catch that catches a superclass object is placed before a catch that catches an object of a subclass of that superclass

  20. The finally Block • The finally block is optional; if it present it must be placed after the last catch block • The finally block can be used to control resource leaks try { // may throw exceptions } catch (ExceptionType1 ref) { // exception handling statements } catch (ExceptionType2 ref) { // exception handling statements } finally { // statements // resource release statements }

  21. The finally Block • A finally block will be executed (if present) regardless of whether or not any exception is thrown and regardless of whether the exception is handled or not. • If there is no exception, it will be executed after the try block • If there is an exception and it is handled by a handler, it will be executed after the catch is completed • If there is an exception and it is not handled by a catch, it will be executed after the termination of the try block and then the exception is passed to to next level • If there is an exception in a catch block, it will be executed after the catch block terminates and then the exception is passed to next level

  22. printStackTrace() and getMessage() • Class Throwable offers a printStackTrace method that prints the method call stack • Class Exception inherits the method • Two constuctors for Exception public Exception() //accept no parameter public Exception(String str) // accept a string • The str stored in Exception may be queried with method getMessage()

  23. printStackTrace & getMessage() public class ExceptionHandling { public static int quotient(int numerator, int denominator) throws DivideByZeroException { if (denominator == 0) throw new DivideByZeroException(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (DivideByZeroException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } }

  24. printStackTrace & getMessage() • The following will be printed by the program • Printed by getMessage() Divide by Zero • Printed by printStackTrace() DivideByZeroException: Divide by Zero at ExceptionHandling.quotient(ExceptionHandling.java:7) at ExceptionHandling.main(ExceptionHandling.java:15)

More Related