Exception handling
IntroductionProgramming errors are unavoidable, even forexperienced programmers. Have three categories of errors:syntax er...
Exception handlingException handling deals with runtime errors. Runtime errors cause exceptions: events that occur  durin...
The Basics of Java Exception Handling   Exception handling       Method detects error which it cannot deal with        ...
The Basics of Java Exception Handling   Format       Enclose code that may have an error in try        block       Foll...
The Basics of Java Exception Handling   Termination model of exception handling       throw point           Place where...
Javaprovides programmers with the capability to handle runtime errors.With this capability, referred to as exception hand...
 To handle the divisor by zero error, use a new construct called the try-catch block to enable the program to catch the e...
Exceptions and Exception TypesVarious reasons for runtime error:   The user enters an invalid input – the program may try...
Catching Exceptionstry {  statements; //Statement that may throw              //exceptions}catch (Exception1 ex) {  handle...
Runtime Errors 1                                        import java.util.Scanner; 2 3                                     ...
Catch Runtime Errors 1                                import java.util.*; 2 3                                public class ...
Exception Classes
System ErrorsSystem errors are thrown by JVMand represented in the Error class.The Error class describes internalsystem er...
ExceptionsException describeserrors caused by yourprogram and externalcircumstances. Theseerrors can be caught andhandled ...
Runtime Exceptions                     RuntimeException is caused by                     programming errors, such as bad  ...
Classifying Java Exceptions   Unchecked Exceptions                               Checked Exceptions    It is not require...
Keywords for Java Exceptions   throws    Describes the exceptions which can be raised by a method.   throw    Raises an ...
Canonical Examplepublic void foo() {    try { /* marks the start of a try-catch block */          int a[] = new int[2];   ...
blocks try {   statements; } catch(TheException ex) {   handling ex; } finally {   finalStatements; }
Trace a Program Execution                           Suppose no exceptions in                           the statementstry {...
Trace a Program Execution                           The final block is always                           executedtry {  sta...
Trace a Program Execution                           Next statement in the                           method is executedtry ...
Trace a Program Executiontry {                    Suppose an exception of type                         Exception1 is throw...
Trace a Program Executiontry {                    The exception is handled.  statement1;  statement2;  statement3;}catch(E...
Trace a Program Executiontry {                    The final block is always                         executed.  statement1;...
Trace a Program Executiontry {                    The next statement in the                         method is now executed...
Trace a Program Executiontry {  statement1;            statement2 throws an  statement2;            exception of type Exce...
Trace a Program Executiontry {  statement1;            Handling exception  statement2;  statement3;}catch(Exception1 ex) {...
Trace a Program Executiontry {  statement1;            Execute the final block  statement2;  statement3;}catch(Exception1 ...
Trace a Program Executiontry {  statement1;            Rethrow the exception and  statement2;            control is transf...
Cautions When Using Exceptions   Exception handling separates error-handling code from    normal programming tasks, thus ...
When to Throw Exceptions   An exception occurs in a method. If you want the    exception to be processed by its caller, y...
When to Use ExceptionsWhen should you use the try-catch block in the code?You should use it to deal with unexpected errorc...
When to Use Exceptionsis better to be replaced byif (refVar != null)  System.out.println(refVar.toString());else  System.o...
Upcoming SlideShare
Loading in …5
×

Comp102 lec 10

332 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
332
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers. Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class). The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).
  • The top example comes from the JDK documentation.
  • Comp102 lec 10

    1. 1. Exception handling
    2. 2. IntroductionProgramming errors are unavoidable, even forexperienced programmers. Have three categories of errors:syntax errors, runtime errors, and logic errors Syntax errors arise because the rules of the language have not been followed detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out Logic errors occur when the program doesn’t perform the way it is intended to
    3. 3. Exception handlingException handling deals with runtime errors. Runtime errors cause exceptions: events that occur during the execution of a program and disrupts the normal flow of control.A program that does not provide code to handle exceptions may terminate abnormally, causing serious problem
    4. 4. The Basics of Java Exception Handling Exception handling  Method detects error which it cannot deal with  Throws an exception  Exception handler  Code to catch exception and handle it  Exception only caught if handler exists  If exception not caught, block terminates
    5. 5. The Basics of Java Exception Handling Format  Enclose code that may have an error in try block  Follow with one or more catch blocks  Each catch block has an exception handler  If exception occurs and matches parameter in catch block  Code in catch block executed try{  If no exception thrown code that may throw exceptions  Exception handling code skipped }  Control resumes after catch blocks catch (ExceptionType ref) { exception handling code }
    6. 6. The Basics of Java Exception Handling Termination model of exception handling  throw point  Place where exception occurred  Control cannot return to throw point  Block which threw exception expires  Possible to give information to exception handler
    7. 7. Javaprovides programmers with the capability to handle runtime errors.With this capability, referred to as exception handling, so you can developrobust programs for mission-critical computing.The following program terminates abnormally because the divisor is 0, whichcauses a numerical error. Note there is no code to explicitly to explicitlyhandle the exceptionpublic class Test{ public static void main(String [] args) { System.out.println(3/0); // Throws ArithmeticException }}
    8. 8.  To handle the divisor by zero error, use a new construct called the try-catch block to enable the program to catch the error and continue to execute.public class test1{ public static void main(String [] args) { try { System.out.println(3/0); } catch (Exception ex) { System.out.println("Error:" + ex.getMessage()); } System.out.println("Execution continues"); }}
    9. 9. Exceptions and Exception TypesVarious reasons for runtime error: The user enters an invalid input – the program may try to open a file that does not exist the network connection may hang up the program may try to access an out of bound s array elementWhen an exception occurs, however, the program may terminate if no handler can be used to deal with it.
    10. 10. Catching Exceptionstry { statements; //Statement that may throw //exceptions}catch (Exception1 ex) { handler for exception1}catch (Exception2 ex) { handler for exception2}...catch (ExceptionN ex) { handler for exceptionN}If no exceptions arise during the executionof the try clause,the catch clauses are skipped.
    11. 11. Runtime Errors 1 import java.util.Scanner; 2 3 public class ExceptionDemo { 4 public static void main(String[] args) { 5 Scanner scanner = new Scanner(System.in); 6 System.out.print("Enter an integer: "); 7 int number = scanner.nextInt(); 8 If an exception occurs on this 9 line, the rest of the lines in the // Display the result method are skipped and the System.out.println(10 program is terminated.11 "The number entered is " + number);12 }13 } Terminated.
    12. 12. Catch Runtime Errors 1 import java.util.*; 2 3 public class HandleExceptionDemo { 4 public static void main(String[] args) { 5 Scanner scanner = new Scanner(System.in); 6 boolean continueInput = true; 7 8 do { 9 try {10 System.out.print("Enter an integer: ");11 int number = scanner.nextInt();12 If an exception occurs on this line,13 the rest of lines in the try block are // Display the result14 skipped and the control is System.out.println(15 transferred to the catch block. "The number entered is " + number);1617 continueInput = false;18 }19 catch (InputMismatchException ex) {20 System.out.println("Try again. (" +21 "Incorrect input: an integer is required)");22 scanner.nextLine(); // discard input23 }24 } while (continueInput);25 }13 }
    13. 13. Exception Classes
    14. 14. System ErrorsSystem errors are thrown by JVMand represented in the Error class.The Error class describes internalsystem errors. Such errors rarelyoccur. If one does, there is littleyou can do beyond notifying theuser and trying to terminate theprogram gracefully.
    15. 15. ExceptionsException describeserrors caused by yourprogram and externalcircumstances. Theseerrors can be caught andhandled by your program.
    16. 16. Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
    17. 17. Classifying Java Exceptions Unchecked Exceptions  Checked Exceptions It is not required that these types of Must either be caught by a method or exceptions be caught or declared on a declared in its signature. method.  Placing exceptions in the method  Runtime exceptions can be generated by signature harkens back to a major methods or by the JVM itself. concern for Goodenough.  Errors are generated from deep within  This requirement is viewed with the JVM, and often indicate a truly fatal derision in the hardcore C++ state. community.  Runtime exceptions are a source of  A common technique for simplifying major controversy! checked exceptions is subsumption.
    18. 18. Keywords for Java Exceptions throws Describes the exceptions which can be raised by a method. throw Raises an exception to the first available handler in the call stack, unwinding the stack along the way. try Marks the start of a block associated with a set of exception handlers. catch If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption. finally Always called when the try block concludes, and after any necessary catch handler is complete.
    19. 19. Canonical Examplepublic void foo() { try { /* marks the start of a try-catch block */ int a[] = new int[2]; a[4] = 1; /* causes a runtime exception due to the index */ } catch (ArrayIndexOutOfBoundsException e) { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); }}/* This code also compiles, but throws an exception at runtime! It * is both less obvious and more common (an off-by-one-error). */public int[] bar() { int a[] = new int[2]; for (int x = 0; x <= 2; x++) { a[x] = 0; } return a;}
    20. 20. blocks try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }
    21. 21. Trace a Program Execution Suppose no exceptions in the statementstry { statements;}catch(TheException ex) { handling ex;}finally { finalStatements;}Next statement;
    22. 22. Trace a Program Execution The final block is always executedtry { statements;}catch(TheException ex) { handling ex;}finally { finalStatements;}Next statement;
    23. 23. Trace a Program Execution Next statement in the method is executedtry { statements;}catch(TheException ex) { handling ex;}finally { finalStatements;}Next statement;
    24. 24. Trace a Program Executiontry { Suppose an exception of type Exception1 is thrown in statement1; statement2 statement2; statement3;}catch(Exception1 ex) { handling ex;}finally { finalStatements;}Next statement;
    25. 25. Trace a Program Executiontry { The exception is handled. statement1; statement2; statement3;}catch(Exception1 ex) { handling ex;}finally { finalStatements;}Next statement;
    26. 26. Trace a Program Executiontry { The final block is always executed. statement1; statement2; statement3;}catch(Exception1 ex) { handling ex;}finally { finalStatements;}Next statement;
    27. 27. Trace a Program Executiontry { The next statement in the method is now executed. statement1; statement2; statement3;}catch(Exception1 ex) { handling ex;}finally { finalStatements;}Next statement;
    28. 28. Trace a Program Executiontry { statement1; statement2 throws an statement2; exception of type Exception2. statement3;}catch(Exception1 ex) { handling ex;}catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements;}Next statement;
    29. 29. Trace a Program Executiontry { statement1; Handling exception statement2; statement3;}catch(Exception1 ex) { handling ex;}catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements;}Next statement;
    30. 30. Trace a Program Executiontry { statement1; Execute the final block statement2; statement3;}catch(Exception1 ex) { handling ex;}catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements;}Next statement;
    31. 31. Trace a Program Executiontry { statement1; Rethrow the exception and statement2; control is transferred to the caller statement3;}catch(Exception1 ex) { handling ex;}catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements;}Next statement;
    32. 32. Cautions When Using Exceptions Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
    33. 33. When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
    34. 34. When to Use ExceptionsWhen should you use the try-catch block in the code?You should use it to deal with unexpected errorconditions. Do not use it to deal with simple, expectedsituations. For example, the following codetry { System.out.println(refVar.toString());}catch (NullPointerException ex) { System.out.println("refVar is null");}
    35. 35. When to Use Exceptionsis better to be replaced byif (refVar != null) System.out.println(refVar.toString());else System.out.println("refVar is null");

    ×