1 / 22

Programming in Java

Programming in Java. Exception Handling 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw. Exception example. try { readFromFile("datafile"); } catch (FileNotFoundException e) { System.err.println("Error: File not found"); }. Exception Handling: Some Options. Print something

shaynad
Download Presentation

Programming in Java

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. Programming in Java Exception Handling 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw

  2. Exception example try { readFromFile("datafile"); } catch (FileNotFoundException e) { System.err.println("Error: File not found"); }

  3. Exception Handling: Some Options • Print something • Throw a new exception • Re-Throw the exception • Fix the problem • Exit

  4. Exception Handling: Printing • You can print a stack trace by calling the exception method printStackTrace() • Sometimes it's better to send error messages to stderr: • System.err.println("Error: invalid thingy"); • Some applications log error messages • file • logging service (syslog).

  5. Exception Handling: throw • You can throw an exception from an exception handler (a catch block). • Allows you to change exception type and/or error message. • You can also alter the base of the stack trace • fillInStackTrace()

  6. Exception example public class ThrowUp { public static void main(String[ ] args) { String tmp; try { // generate an ArrayIndexOutOfBoundsExceptions .. // .. (on purpose!). for (int i=0 ; i<args.length+10 ; i++) { tmp = args[i]; } System.out.println("I made it!"); } catch (ArrayIndexOutOfBoundsException up) { throw new SecurityException("Trouble"); } } // main }

  7. Exception Handling: Re-throw • You can throw an exception from an exception handler (a catch block) without changing anything: • called rethrowing • The caller needs to deal with the exception. • This also happens if you don't catch the exception! • sometimes you need to take some action and then rethrow the exception.

  8. Another way to re-throw • You can allow selected types of exceptions to be propogated to the caller of your method: void blah() throws IOException { • Within blah() you don't need to catch these exceptions (to be able to compile).

  9. Exception Handling: Fix the problem. • You can't fix things and then resume execution automatically • you can do this in C++. • You can have a loop the retries the code again.

  10. Exception Handling: exiting • Sometimes the error is fatal, and you want to stop the program immediately. • System.exit();

  11. Wait.java public class Wait { public static void main(String[ ] args) { boolean done=false; int seconds=0; try { seconds = Integer.parseInt(args[0]); } catch (Exception e) { System.out.println("Please specify the number of seconds"); System.exit(1); } long initialtime = System.currentTimeMillis( ); while (!done) { try { if (System.currentTimeMillis()-initialtime < seconds*1000) throw new Exception("Not Yet - keep trying"); done=true; } catch (Exception e) { System.out.println(e); } } System.out.println("Done!\n"); } }

  12. How/when do you generate exceptions? • Use throw: throw new Exception("broken!"); • You can use throw anywhere. • you detect some error that means the following code should not be executed. • In some cases, you can think of throw as an alternate return

  13. Exception Enforcement • In general, you do the following: • specify what exceptions each method can generate. (throw) • write code to catch all exceptions that can be generated by a method call. • The compiler (usually) enforces this • it is a compilation error to call a method without catching it's declared exception types.

  14. RunTime Exceptions • There are exceptions that are generated by the system (that are usually caused by programming mistakes): • NullPointerException (null references) • ArrayIndexOutOfBoundsException • If you don't catch these, a stack trace will be generated and the program will terminate. • The compiler does not force you to catch these exceptions.

  15. Exception Types • Exceptions are objects! • Exception types are classes. • A (quite large!) hierarchy of classes. • All exception types are derived from the class Exception • there are some methods defined in this base class.

  16. NullPointer.java import java.util.*; public class NullPointer { public static void main(String[ ] args) { Date f = new Date(); f=null; PrintSomething2(f); // comment out to test PrintSomething PrintSomething(f); } // no checks, if x is null runtime exception default behavior static void PrintSomething(Object x) { System.out.println(x.getClass( ).getName()); } // we explicitly check for runtime exception! static void PrintSomething2(Object x) { try { System.out.println(x.getClass().getName()); } catch (RuntimeException re) { System.out.println("Fatal Error!"); System.exit(1); } } // main }

  17. Exception Error Exception Type Hierarchy (partial) Throwable VirtualMachineError RunTimeException IOException NullPointerException EOFException ArithmeticException

  18. Some Exception Methods • These are actually inherited from throwable printStackTrace() fillInStackTrack() getMessage()

  19. Creating Your Own Exception Types • It is often useful to create your own type of exception. • generally all you create is a name. • you can get fancy and add new methods to your exception class(es). User-defined Exception Type class FooException extends Exception { } // .. class BlahException extends Exception { BlahException(){} BlahException(String s) { super(s); } } // .. throw new BlahException("Invalid blah");

  20. using finally try { statements . . . } catch (ExceptionType1 ename1) { error handling statements . . . } catch (ExceptionType2 ename2) { error handling statements . . . } finally { … this code always executed … }

  21. Why finally? • What is there to clean up? • No memory cleanup required in Java! • No destructors to call! • Sometimes you need to set the state of things (fields) to some stable (acceptable) state.

  22. Exception Handling 謝謝捧場 http://www.csie.nctu.edu.tw/~tsaiwn/oop/ 蔡文能

More Related