Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.

Similar presentations


Presentation on theme: "CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things."— Presentation transcript:

1 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things go TRAGICALLY AWRY

2 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 2 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 3 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 4 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 5 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 6 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 7 CPSC150 Throwing an exception public void setDenominator(int den) { if(den == 0) { throw new Exception(“Divide by 0"); } denominator = den; }

8 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 8 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 9 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 10 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 11 CPSC150 The try-catch statement 1. Exception thrown from here 2. Control transfers to here 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"); }

12 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 12 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 13 CPSC150 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 Order of statement execution 2a. continue with rest of try 3a. skip catch, do code after try- catch Case a: no exception thrown

14 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 14 CPSC150 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 Order of statement execution 1. if method call, do method 2b. skip rest of try; do code in catch 3b. if catch code does not abort program, continue after catch block Case b: TypeOfException thrown

15 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 15 CPSC150 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 Order of statement execution 1. if method call, do method 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 Case c: DifferentException thrown

16 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 16 CPSC150 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; } An Exception Example

17 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 17 CPSC150 Write a main method that calls divideByY Write a main method that has try-catch block

18 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 18 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 19 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 20 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 21 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 22 CPSC150 Catching multiple exceptions tried 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 23 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 24 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 25 CPSC150 The exception class hierarchy

26 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 26 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 27 CPSC150 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 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 28 CPSC150 Some Checked Exceptions –ClassNotFoundExceptionClassNotFoundException –IOExceptionIOException –NoSuchFieldExceptionNoSuchFieldException –ServerNotActiveExceptionServerNotActiveException –UnsupportedFlavorExceptionUnsupportedFlavorException

29 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 29 CPSC150 The throws clause Methods throwing a checked exception must handle the exception or include a throws clause: public void saveToFile(String destinationFile) throws IOException (NOT throw) throw is when the exception is thrown

30 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 30 CPSC150 throws must include throws in methods that throw checked exceptions how do I know? javadoc/syntax errors

31 CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 31 CPSC150 Text input-output: tie to exceptions java.io.IOException is a checked exception. cannot do files without exceptions


Download ppt "CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things."

Similar presentations


Ads by Google