重庆大学java课件
Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; * Handling exception Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; * Execute the final block Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; * Rethrow the exception and control is transferred to the caller 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. * 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 * try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } When to Use Exceptions is better to be replaced by * if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); Defining Custom Exception Classes Use the exception clas