1 / 31

Exceptions

Exceptions. When things go TRAGICALLY AWRY. How things go TRAGICALLY AWRY. User enters bad data Programmer makes a mistake Another method/program passes bad data to a method System problems happen. When others use your program.

stacey
Télécharger la présentation

Exceptions

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. Exceptions When things go TRAGICALLY AWRY

  2. How things go TRAGICALLY AWRY • User enters bad data • Programmer makes a mistake • Another method/program passes bad data to a method • System problems happen

  3. When others use your program • Check values being returned are reasonable. Don't do actions that will cause problems • Create return value that indicates a problem so clients can: • Attempt recovery on error • Avoid program failure • Ignore the return value • Cannot be prevented • Likely to lead to program failure • Create something client cannot ignore: • an exception

  4. Exception-throwing principles • Exceptions are part of many languages, central to Java. • A special language feature. • No ‘special’ return value needed. • Errors cannot be ignored in the client. • The normal flow-of-control is interrupted. • Specific recovery actions are encouraged.

  5. Exceptions • Exceptions are “thrown” by the method finding the problem • Exceptions are “caught” by the method dealing with the problem • maintains integrity and decoupling

  6. The effect of an exception • The throwing method finishes prematurely. • No return value is returned. • Control does not return to the client’s point of call. • So the client cannot carry on regardless. • A client may ‘catch’ an exception.

  7. Throwing an exception public void setDenominator(int den) { if(den == 0) { throw new Exception(“Divide by 0"); } denominator = den; }

  8. Throwing an exception • An exception object is constructed: • new ExceptionType("..."); • Most often, use existing Exception types • The exception object is thrown: • throw ... • Most often, exception is thrown by java classes, not programmer-defined

  9. Error recovery • Clients should take note of error notifications. • Check return values. • Don’t ‘ignore’ exceptions. • Include code to attempt recovery. • Will often require a loop.

  10. Handling Exceptions:The try-catch statement • Clients catching an exception must protect the call with a try statement:try {// put statements here that might throw an // exception }catch(Exception e) { // Report and recover from the // exception here.}

  11. The try-catch statement Fraction f; try { f.setDenominator(n); // n is an already defined with a value } catch (ArithmeticException ex) { System.out.println("you dummy, use something other than 0"); } 1. Exception thrown from here 2. Control transfers to here

  12. try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception

  13. Order of statement execution Case a: no exception thrown 1. if method call, do method try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception 2a. continue with rest of try 3a. skip catch, do code after try-catch

  14. Order of statement execution Case b: TypeOfException thrown 1. if method call, do method try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception 2b. skip rest of try; do code in catch 3b. if catch code does not abort program, continue after catch block

  15. Order of statement execution Case c: DifferentException thrown 1. if method call, do method try { // code that might throw an exception { catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception 2c. skip rest of try; do not do catch; exit from this method at the code in try; do not do any other code 3c. No other code in this method is executed. catch code and code afterwards is skipped

  16. An Exception Example public class George { private int x; public George() { x = 0; } public int divideByY(int y) { if (y == 0) { throw new ArithmeticException( "in divideByY, y, a denominator, is 0"); } y= x /y; return y; } }

  17. Write a main method that calls divideByY • Write a main method that has try-catch block

  18. public static void main(String[] args) { George m = new George(); System.out.println("m with 4 is " + m.divideByY(4)); System.out.println("m with 0 is " + m.divideByY(0)); System.out.println("all done"); } // end main } // end class

  19. public static void main(String args[ ]) {George m = new George(); try { System.out.println("m with 4 is " + m.divideByY(4)); System.out.println("m with 0 is " + m.divideByY(0)); } catch (ArithmeticException e) { System.out.println("don't call method with 0 as parameter"); e.printStackTrace(); } System.out.println("all done"); }

  20. Try-Catch second chance • Can put try-catch blocks in a loop. • if catch block not entered, exit loop • if catch block entered, print a message; ask the user to fix the problem • if catch block entered too many times, give up

  21. public class Test { public static void main(String args[]) { int n = 0; Scanner kbd = new Scanner(System.in); int mynbr; String s = null; boolean valid = false; while (!valid && n<3) { try { System.out.print(“Enter an integer: ”); mynbr = kbd.nextInt( ); valid = true; } catch (Exception georgette) { System.out.print(“You must enter a valid integer-> ”); n++; } }// end of loop if (valid) System.out.println("The number is " + mynbr ); } }

  22. Catching multiple exceptionstried in order that they appear try { ... ref.process(); ... } catch(EOFException e) { // Take action on an end-of-file exception. ... } catch(IOException e) { // Take action on any other IOexception. ... }

  23. The finally clause try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. }

  24. The finally clause: why • A finally clause is executed even if a return statement is executed in the try or catch clauses. • A uncaught or propagated exception still exits via the finally clause.

  25. The exception class hierarchy

  26. Exception categories • Checked exceptions: extra syntax required • Subclass of Exception • Use for anticipated failures. • Where recovery may be possible. • Often not a programming problem (e.g., file not found) • Unchecked exceptions: extra syntax NOT required • Subclass of RuntimeException • Use for unanticipated failures. • Where recovery is unlikely. • Often, a programming problem (e.g., index out of bounds) • Third category: errors

  27. Checked Exceptions • Previous examples all unchecked exceptions • Checked exceptions are meant to be caught. • The compiler ensures that their use is tightly controlled. • In both server and client. • Used properly, failures may be recoverable.

  28. Some Checked Exceptions • ClassNotFoundException • IOException • NoSuchFieldException • ServerNotActiveException • UnsupportedFlavorException

  29. The throws clause • Methods throwing a checked exception must handle the exception or include a throwsclause:public void saveToFile(String destinationFile)throws IOException • (NOT throw) throw is when the exception is thrown

  30. throws • must include throws in methods that throw checked exceptions • how do I know? • javadoc/syntax errors

  31. Text input-output:tie to exceptions • java.io.IOException is a checked exception. • cannot do files without exceptions

More Related