1 / 28

Chapter 13 Exception Handling

Chapter 13 Exception Handling. Claiming Exceptions Throwing Exceptions Catching Exceptions Rethrowing Exceptions The finally Clause Cautions When Using Exceptions Exception Types. Mistakes happen. No matter how well designed a program is, there is

beatrizh
Télécharger la présentation

Chapter 13 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. Chapter 13 Exception Handling • Claiming Exceptions • Throwing Exceptions • Catching Exceptions • Rethrowing Exceptions • The finally Clause • Cautions When Using Exceptions • Exception Types

  2. Mistakes happen No matter how well designed a program is, there is always the chance that some kind of error will arise during its execution. • Attempting to divide by 0; • Attempting to read from a file which does not exist; • Referring to non-existing item in array; • etc. An exception is an event that occurs during the execution of a program that disrupt its normal course.

  3. Main idea • Java was designed with the understanding that errors occur, that unexpected events happened and the programmer should always be prepared for the worst. • The preferred way of handling such conditions is to use exception handling, an approach that separates a program’s normal code from its error-handling code.

  4. Example: Open file and read contents ask the user for the name of a file open the file read the contents do something with the contents close the file Does the file exist? Can we open the file? Can we read data from the file?

  5. Exceptions • Exception is a useful programming construct because the location where an error is detected is usually not the place where the appropriate solution is known. • Constructors are not permitted to return a null value, furthermore there might be multiple reasons for a failure. • Does a null value returned by a file open operation mean the file does not exist, or that it exists but cannot be read? Finally, what if a null value is perfectly legal?

  6. Claiming, Throwing, and Catching Exceptions

  7. Example 1a: Division • When a statement causes error, the method containing the statement creates exception object and passes it to the system. Class Test { public static main(String args[]) { int d, a; d = 0; a = 1/d; } } Output: java.lang.ArithmeticException: / by zero at samples.Test.main(Test.java:5)

  8. Exception handling • After a method throws an exception, the Java runtime system begins the process of finding the code to handle the error. • The code that handles the error is called the exceptionhandler;it is foundby searching backward through a chain of method calls, starting from the current method. • The process of finding a handler is called catching an exception. • If no handler is found, the program terminates.

  9. Example 1b: Division int d, a; d = 0; try { a = 1/d; System.out.println(“It will not be printed”); } catch (ArithmeticException except) { System.out.println(“Division by zero!”); } System.out.println(“After catch statement.”); Output: Division by zero! After catch statement.

  10. Example 1c: Division int d, a; d = 0; try { // The method now claims an exception and throws it if the divisor is zero. if(d==0) throw new RuntimeException(); a = 1/d; } catch (RuntimeException except) { System.out.println(except); } System.out.println(“After catch statement.”); Output: java.lang.RunTimeException After catch statement.

  11. Example 2: String to integer String str1=“123”, str2=“xwz”; try { int i1 = Integer.parseInt(str1); System.out.println(“The 1st int value ” + i1); int i2 = Integer.parseInt(str2); System.out.println(“The 2nd int value ” + i2); } catch (NumberFormatException exc) { System.out.println(exc); } … Output The 1st int value is 123 java.lang.NumberFormatException: For input string: "xwz"

  12. Exceptions handling 1. Claiming Exceptions 2. Throwing Exceptions 3. Catching Exceptions

  13. 1. Claiming Exceptions To claim an exception in a method, use the throws keyword. modifiers MethodName(list of params) throws Exception_1, Exception_2, ..., Exception_N Example: public void myMethod() throws IOException { ... }

  14. Claiming Exception Example // The method divide(k,m) returns result of division, // n = k/m; public int divide(int k, int m) throws RuntimeException { ... }

  15. 2. Throwing Exceptions In the method that has claimed the exception, you can throw an object of the exception if the exception arises. throw new TheException(); TheException e = new TheException(); throw e;

  16. Throwing Exceptions Example public int divide(int k, int m) throws RunTimeException { if(m == 0) { throw new RuntimeException(”Divisor can’t be zero"); } return k/m; }

  17. 3. Catching Exceptions try { statements; } catch(Exception1 e){ handler for exception1; } catch (Exception2 e) { handler for exception2; } ... catch (ExceptionN e){ handler for exceptionN; }

  18. Catching Exceptions Example try { int n = divide(k,m); } catch(RuntimeException e){ System.out.println(“Error! Division by 0.”); }

  19. Methods of Exception object • public String getMessage() // Returns detailed message of the object • public String toString() // Returns short description of the object • public void printStackTrace() // Print trace information: class name, method name, file name, and line number. java.lang.ArithmeticException: /by zero at MyClass,divide(MyClass.java:5)

  20. Open File Example, cont. try { File fd = new File(filename); processFile(fd); fd.close() } catch (FileNotFound e) { System.out.println(“Cannot find file”+e); e.printStackTrace(); } catch (FileOpenFailed e) { System.out.println(“Cannot open file”+e); e.printStackTrace(); }

  21. Claiming, Throwing, and Catching Exceptions

  22. Rethrowing Exceptions try { statements; } catch(TheException e) { perform operations before exits; throw e; }

  23. Catching Exceptions

  24. The finally Clause • You may want some code to be executed regardless of whether an exception occurs or is caught. Java has a finally clause that can accomplish this objective. try { statements; } catch(TheException1 e) { handling e; } catch(TheException2 e) { handling e; } finally { finalStatements; }

  25. The finally Clause • If no exception arises in the try block, finalStatementisexecuted. • If one of the statements causes an exception in try block that is caught in a catch clause, the other statements in try block are skipped, the catch clause is executed, and the finally clause isexecuted. * If the catch clause does not rethrow an exception, the next statement is executed. * If it does, the exception is passed to the caller of the method. • If one of the statements causes an exception is not caught in any catch clause, the other statements in the try block are skipped, the finally clause isexecuted, and the exception is passed to the caller of this method.

  26. Example: finally Suppose that statement2 causes an exception ex2: try { statement1; statement2; statement3; } catch(TheException1 ex1) { handling ex1; } catch(TheException2 ex2) { handling ex2; } finally { finalStatement; } statement 4; Output: statement1; finalStatement; statement4;

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

  28. Exceptions and Exception Types

More Related