310 likes | 453 Views
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.
E N D
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 • 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
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.
Exceptions • Exceptions are “thrown” by the method finding the problem • Exceptions are “caught” by the method dealing with the problem • maintains integrity and decoupling
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.
Throwing an exception public void setDenominator(int den) { if(den == 0) { throw new Exception(“Divide by 0"); } denominator = den; }
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
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.
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.}
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
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 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
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
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
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; } }
Write a main method that calls divideByY • Write a main method that has try-catch block
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
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"); }
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
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 ); } }
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. ... }
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. }
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.
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
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.
Some Checked Exceptions • ClassNotFoundException • IOException • NoSuchFieldException • ServerNotActiveException • UnsupportedFlavorException
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
throws • must include throws in methods that throw checked exceptions • how do I know? • javadoc/syntax errors
Text input-output:tie to exceptions • java.io.IOException is a checked exception. • cannot do files without exceptions