Document Details

RefreshedPanFlute

Uploaded by RefreshedPanFlute

جامعة أسيوط الجديدة التكنولوجية

Tags

exception handling java programming programming computer science

Summary

This document discusses exception handling in Java programming. It covers different types of exceptions, how to handle them, and when to use exceptions.

Full Transcript

EXCEPTION HANDLING Exception-Handling Overview When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? 2 Exception-Handling Overview Show runtime error 3 Excep...

EXCEPTION HANDLING Exception-Handling Overview When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? 2 Exception-Handling Overview Show runtime error 3 Exception-Handling Overview Fix it using an if statement 4 Exception-Handling Overview With a method System.exit(status): The status parameter indicates the exit status of the program. 0 means that the program terminated successfully (normal termination). 1 or any non-zero value indicates that the program terminated due to an error or abnormal condition. 5 Exception Advantages It enables a method to throw an exception to its caller. Without this capability, a method must handle the exception or terminate the program. 6 Handling InputMismatchException By handling InputMismatchException, your program will continuously read an input until it is correct. 7 Exception Types Exceptions are objects, and objects are defined using classes. The root class for exceptions is java.lang.Throwable. ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes 8 System Errors ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes System errors are thrown by JVM LinkageError and represented in the Error class. The Error class describes internal Error VirtualMachineError system errors. Such errors rarely occur. If one does, there is little Many more classes you can do beyond notifying the user and trying to terminate the program gracefully. 9 Exceptions Exception describes errors caused by your program ClassNotFoundException and external circumstances. ArithmeticException These errors can be caught IOException and handled by your Exception NullPointerException program.. RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes 10 Runtime Exceptions ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError RuntimeException is caused by programming errors, such as bad Error VirtualMachineError casting, accessing an out-of-bounds array, and numeric errors. Many more classes 11 Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions in a try-catch block or declare it in the method header. 12 Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions. 13 Unchecked Exceptions ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Unchecked exception. Many more classes 14 Declaring, Throwing, and Catching Exceptions Java’s exception-handling model is based on three operations: declaring an exception, throwing an exception, and catching an exception, 15 Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. 16 Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, 17 Catching Exceptions 18 Catching Exceptions 19 Catch or Declare Checked Exceptions Suppose p2 is defined as follows: void p2() throws IOException { if (a file does not exist) { throw new IOException("File does not exist"); }... } 20 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { void p1() throws IOException { try { p2(); p2(); } catch (IOException ex) { }... } } (a) (b) 21 Example: Declaring, Throwing, and Catching Exceptions 22 The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } 23 Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; 24 Trace a Program Execution The final block is try { always executed statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; 25 Trace a Program Execution Next statement in the try { method is executed statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; 26 Trace a Program Execution try { Suppose an exception statement1; of type Exception1 is statement2; thrown in statement2 statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; 27 Trace a Program Execution try { The exception is statement1; handled. statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; 28 Trace a Program Execution try { The final block is statement1; always executed. statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; 29 Trace a Program Execution try { The next statement in statement1; the method is now statement2; executed. statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; 30 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. 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. 35 When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code is better to be replaced by 36 37 Thanks

Use Quizgecko on...
Browser
Browser