cpsc150 click to edit master title style click to edit master text styles second level third level...
Post on 19-Dec-2015
227 views
TRANSCRIPT
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
1CPSC150
Exceptions
When things go TRAGICALLY AWRY
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
2CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
3CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
4CPSC150
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.
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
5CPSC150
Exceptions
• Exceptions are “thrown” by the method finding the problem
• Exceptions are “caught” by the method dealing with the problem
• maintains integrity and decoupling
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
6CPSC150
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.
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
7CPSC150
Throwing an exception
public void setDenominator(int den){ if(den == 0) { throw new Exception(“Divide by 0"); } denominator = den;}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
8CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
9CPSC150
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.
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
10CPSC150
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.}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
11CPSC150
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");
}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
12CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
13CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
14CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
15CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
16CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
17CPSC150
• Write a main method that calls divideByY
• Write a main method that has try-catch block
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
18CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
19CPSC150
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"); }
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
20CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
21CPSC150
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 ); }}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
22CPSC150
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. ...}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
23CPSC150
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.}
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
24CPSC150
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.
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
25CPSC150
The exception class hierarchy
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
26CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
27CPSC150
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.
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
28CPSC150
Some Checked Exceptions
– ClassNotFoundException– IOException– NoSuchFieldException– ServerNotActiveException– UnsupportedFlavorException
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
29CPSC150
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
CPSC150
Click to edit Master title style
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
30CPSC150
throws
• must include throws in methods that throw checked exceptions
• how do I know?
• javadoc/syntax errors