Exception handling

2,496 views
2,300 views

Published on

JAVA EXCEPTION HANDLING
N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar

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
2,496
On SlideShare
0
From Embeds
0
Number of Embeds
1,350
Actions
Shares
0
Downloads
50
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • What exceptions can occur in this code fragment? NullPointerException ArithmeticException: / By Zero
  • What exceptions can occur in this code fragment? IOException NumberFormatException ArithmeticException – DivideByZero NegativeArraySizeException
  • What exceptions can occur in this code fragment? IOException NumberFormatException ArithmeticException – DivideByZero NegativeArraySizeException
  • Create Exception Hierarchy Handout (online and hardcopy for class) Link to this for "Java Exceptions" web page.
  • catch block must match the class of exception that occurs
  • Exception handling

    1. 1. Exception Handling
    2. 2. Throwing Exceptions What is a good program? A program that is reliable? Not just giving correct answer on correct input Should protect against possible errors (invalid password, not a picture file, etc)
    3. 3. Good programs Need a robust program, reliable in the eyes of a novice user It should not (“cannot”) crash easily - what if Word always crashed when you hit the control key?
    4. 4. Good Programs How do we ensure a robust program? Option 1 – return a special value to determine if the method succeeded or failed  Ex. Make withdraw return true or false What’s wrong with this?  Calling method may not check answer  Calling method may not know what to do
    5. 5. Good Programs Option 2 - Use exceptions Exception – an error condition that can occur during the normal course of a program execution Exception handling is another form of control structure (like ifs and switch statements)  When an error is encountered, the normal flow of the program is stopped and the exception is handled
    6. 6. Exceptions We say an exception is thrown when it occurs When the exception-handling code is executed, the error is caught Examples:  Dividing by zero  Accessing a null object
    7. 7. Exceptions What happens when exceptions occur?  An Exception object is thrown What happens when an Exception is thrown?  normal execution stops and exception handling begins What does the Exception object know?  the name of the problem  the location where it occurred  and more…
    8. 8. Exceptions Why use exceptions? consistency (everyone else does it)  Java API classes use exceptions.  Other programming languages do too! flexibility  programmer can decide how to fix problems. simplicity  Easy to pinpoint problems.
    9. 9. Handling Exceptions Do nothing  program crashes if the exception occurs! Propagate (throw) it  tell the method’s caller about it and let them decide what to do Resolve (try-catch) it in our method  fix it or tell the user about it and let them decide what to do
    10. 10. Handling Exceptions So far, we have let the system handle exceptionsint score = in.nextInt();If the user enters “abc123”Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at Test.main(Test.java:5)
    11. 11. Handling Exceptions Says in English:  System has caught an error described as a InputMismatchException  Thrown because a String cannot be converted to an integer When system handles, we often get a program crash Instead of the system, we can handle to improve robustness
    12. 12. Handling Exceptions Better solution: Instead of letting the program crash, use Exception Handling to improve program’s robustness  Exceptions cannot be ignored  Exceptions are handled by Exception Handlers directly
    13. 13. Throwing Exceptions If there is an error in the value of a parameter, we can throw exceptions to make the user accountable1. Decide what type of exception to throw2. Test for condition, and throw the exception if condition is violated
    14. 14. Example Throw an exception object to signal an exceptional condition Example: What do we do if the amount to withdraw is greater than the balance?  IllegalArgumentException: illegal parameter value
    15. 15. Problempublic class BankAccount{ public void withdraw(double amount) { if (amount > balance) { ????????? } balance = balance - amount; }. . .}
    16. 16. Solution #1public class BankAccount{ public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }. . .}
    17. 17. Solution #2public class BankAccount{ public void withdraw(double amount) { if (amount > balance) { throw new IllegalArgumentException("Amount exceeds balance"); } balance = balance - amount; }. . .}
    18. 18. Throwing Exceptions: Syntaxthrow exceptionObject;
    19. 19. Checked/Unchecked Exceptions Checked Exception – checked at compile time  Complier ensures that you are handling a possible problem  These errors are due to external circumstances that the programmer cannot prevent  Majority occur when dealing with input and output  For example, IOException
    20. 20. Checked/Unchecked Exceptions Unchecked Exception = Runtime Exceptions  Extend the class RuntimeException or Error  They are the programmers fault  Examples of runtime exceptions:  NumberFormatException  IllegalArgumentException  NullPointerException  Optional to deal with these Example of error: OutOfMemoryError  Can’t do anything about these catastrophic problems, so don’t deal with it
    21. 21. Checked/Unchecked Exceptions Unchecked Exceptions result from deficiencies in your code, so should check on own  Null object reference  Sending a negative value to Math.sqrt() Checked Exceptions are not the fault of the coder  Problems with the file format, user input, etc.
    22. 22. Checked/Unchecked Exceptions Categories arent perfect:  Scanner.nextInt throws unchecked InputMismatchException  Programmer cannot prevent users from entering incorrect input  This choice makes the class easy to use for beginning programmers
    23. 23. Checked/Unchecked Exceptions Deal with checked exceptions principally when programming with files and streams For example, use a Scanner to read a fileString filename = . . .;FileReader reader = new FileReader(filename);Scanner in = new Scanner(reader); But, FileReader constructor can throw a FileNotFoundException
    24. 24. Handling Checked Exceptions1. Handle the exception2. Tell compiler that you want method to be terminated when the exception occurs  Use throws specifier so method can throw a checked exceptionpublic void read(String filename) throws FileNotFoundException{ FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . .}
    25. 25. Handling Checked Exceptions throws tells the compiler to “pass the buck” to the method that called this method Can propagate multiple exceptions:public void read(String filename) throws IOException, ClassNotFoundException Can also group using hierarchy  If method can throw an IOException and FileNotFoundException, only use IOException
    26. 26. Handling Checked Exceptions Why propagate when we could handle the error ourselves?  We may not know how to  Let user of my code decide Better to declare exception than to handle it incompetently
    27. 27. Catching Exceptions At some point, an exception should be dealt with  If not, program terminates with error message Professional code requires more sophistication – cannot just allow errors to kill program  What would happen if all of my.wisc.edu turned off if you entered wrong password?
    28. 28. Catching Exceptions To deal with this problem, install exception handlers in your code to deal with possible exceptions Handlers are try/catch statements
    29. 29. Try-Catch Put statement(s) that could cause an error in the try block Error handling code goes in catch block  Only is executed if there was an error Can have multiple catch blocks, one for each possible type of exception
    30. 30. try-catch Syntaxtry{ <try block>}catch ( <ExceptionClass> <name> ){ <catch block>}catch ( <ExceptionClass> <name> ){ <catch block>}…
    31. 31. try{ String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . .}catch (IOException exception){ exception.printStackTrace();}catch (NumberFormatException exception){ System.out.println("Input was not a number");}
    32. 32. Example 3 types of error can be thrown  FileNotFoundException is thrown by FileReader constructor  caught by IOException clause  NoSuchElementException is thrown by Scanner.next  not caught, thrown to caller  NumberFormatException is thrown by Integer.parseInt()  caught by second clause
    33. 33. Catching Exceptions If there are no errors, the catch block is skipped If an exception is thrown, the try block stops executing immediately and jumps to the catch block
    34. 34. Catching Exceptions
    35. 35. Exception Information Why do we have Exception objects?  We can get information on where the error happened and what exactly happened Exception objects have 2 methods defined:  getMessage() (what happened?)  printStackTrace() (where did it happen?)
    36. 36. getMessage Returns the data that cause the error  Example: … }catch(NumberFormatException e){ System.out.println(e.getMessage()); }
    37. 37. printStackTrace Prints out a trace of methods that caused the error starting at the root of the error  Where did the exception occur? What method called this code to execute..etc.  This is what the system does when an exception is thrown  Example: … }catch(NumberFormatException e){ e.printStackTrace(); }
    38. 38. Catching ALL Exceptionspublic double average( String data ){ try { int sum = 0; for ( int i=0; i < data.length(); i++ ) sum += Integer.parseInt(data.charAt(i)); return sum/data.length(); } catch ( Exception e ) // catch ALL exceptions { System.out.println( e ); return 0; }}
    39. 39. Catching ALL Exceptions Why is this probably a bad idea? Probably want to handle each type of exception differently Dont want to catch things like NullPointerExeption
    40. 40. Catching Exceptions IMPORTANT! Order of catch blocks matters } catch (Exception e){ System.out.println(e.getMessage()); } catch (NumberFormatException e){ System.out.println("" + str + "not valid input, Please use digits only"); } You should go specific to generic  NumberFormatException is a specific type of the class Exception (inheritance)
    41. 41. Demop.s.v. main( String [] args ){ try { String filename = args[0], input; scanner = new Scanner( new File(filename) ); input = scanner.nextLine(); int value = Integer.parseInt( input ); double reciprocal = 1.0 / value; System.out.println( "rec=" + rec ); } catch ( Exception e ) { S.o.pln( "Found Exception: " + e ); } S.o.pln( "Done" );}
    42. 42. String filename=args[0], input;try { scanner = new Scanner(new File(filename)); input = scanner.nextLine(); int value = Integer.parseInt( input ); double reciprocal = 1.0 / value; System.out.println( "rec=" + rec );}catch ( NumberFormatException e ) { S.o.pln( input + " is not an integer");}catch ( ArithmeticException e ) { S.o.pln( "Cant divide by zero" );}catch ( FileNotFoundException e ) { S.o.pln( filename + " Not Found" );}finally { S.o.pln( "Done" ); }
    43. 43. Catching Exceptions What if an exception is thrown and there is no catch block to match?  The system handles it (terminates program and prints the stack trace)
    44. 44. The finally clause Recall that whenever an exception occurs, we immediately go to the catch block What if there is some code we want to execute regardless of whether there was an exception?  finally block is used
    45. 45. The finally clausetry{ distance = Double.parseDouble(str); if (distance < 0){ throw new Exception("Negative distance is not valid"); } return distance;} catch (NumberFormatException e){ System.out.println("" + str + "not valid input, Please use digits only");} catch (Exception e){ System.out.println(e.getMessage());} finally { System.out.println(“Done”);}
    46. 46. The finally clause finally is executed NO MATTER WHAT Even if there is a break or return in the try block Good for “cleanup” of a method
    47. 47. Throwable Exception Inheritance Hierarchy Exception RuntimeException NullPointerException ArithmeticException NegativeArrayIndexException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException IllegalArgumentException NumberFormatException IOException FileNotFoundException EOFException
    48. 48. try-catch Control Flowcode before try try blockno exceptions occur code after try
    49. 49. try-catch Control Flowcode before try exception occurs try block catch blockcode after try
    50. 50. try-catch Control Flowcode before try exception occurs try block catch blockno exceptions occur code after try
    51. 51. try-catch Control Flow code before try try blockno exceptions occurred finally block (if it exists) code after try
    52. 52. try-catch Control Flow code before try exception occurs try block catch blockfinally block (if it exists) code after try
    53. 53. try-catch Control Flow exception occurs code before try true matches first try block catch block?no exceptions occurred 1st catch block false true matches next 2nd catch block catch block? false finally block (if it exists) code after try
    54. 54. Propagating Exceptions When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types:  a catcher, or  a propagator.
    55. 55. Propagating Exceptions An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.
    56. 56. Example The following figure shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.
    57. 57. Example
    58. 58. Propagating Exceptions If a method is an exception propagator, we need to modify its header to declare the type of exceptions the method propagates. We use the reserved word throws for this declaration. public void C( ) throws Exception { ... } public void D( ) throws Exception { ... }
    59. 59. Propagating Exceptions Without the required throws Exception clause, the program will not compile. However, for exceptions of the type called runtime exceptions, the throws clause is optional.
    60. 60. Propagating vs. Catching Do not catch an exception that is thrown as a result of violating a condition set by the client programmer. Instead, propagate the exception back to the client programmer’s code and let him or her handle it.
    61. 61. Exceptions in a Constructor We can thrown an exception in the constructor if a condition is violated  For example, we may throw an IllegalArgumentException if a parameter value is invalid

    ×