exceptions & exception handling
DESCRIPTION
Exceptions & exception handling. Exceptions & exception handling. Use sparingly. Things you can do with exceptions: Define a new exception class. Create an exception instance. Throw an exception. Declare that an exception may be thrown (in a particular function). - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/1.jpg)
![Page 2: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/2.jpg)
Exceptions & exception handlingUse sparingly.
Things you can do with exceptions:1. Define a new exception class.2. Create an exception instance.3. Throw an exception.4. Declare that an exception may be thrown (in a
particular function).5. Handle the possibility that an exception may
be thrown.
![Page 3: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/3.jpg)
1. Define a new exception classextend Exception (or extend a subclass of
Exception)See
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Exception.html.
This creates a new type.All have a ctor w/ a single String arg.Each has an accessor method called
getMessage() that returns the String from the ctor arg.
![Page 4: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/4.jpg)
Define a new exception class example//typical sample codepublic class DivisionByZeroException extends Exception {
public DivisionByZeroException ( ) {super( “Division by zero!” );}
public DivisionByZeroException ( String message ) {super( message );}
}
![Page 5: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/5.jpg)
Define a new exception class example (w/ more information)
public class BadNumberException extends Exception {
private int mBadNumber;
public BadNumberException ( ) {super( “BadNumberException”
);}
public BadNumberException ( String message ) {
super( message );}
public BadNumberException ( int number ) {super( “BadNumberException” );mBadNumber = number;}
public int getBadNumber ( ) {return mBadNumber;}
}
![Page 6: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/6.jpg)
2. Create an exception instanceEx.
new Exception( “Uh oh!” );Exception e = new Exception( “Rats!” );
![Page 7: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/7.jpg)
3. Throw an exceptionEx.
throw new Exception( “Invalid value.” );
Exception e = new Exception( “Invalid age.” );throw e;
![Page 8: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/8.jpg)
4. Declare (a method that indicates) that an exception may be thrownEx.
public int f ( int x ) throws Exception {…
}
![Page 9: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/9.jpg)
5. Handle the possibility that an exception may be thrownThe try-catch blocks:
try {…
} catch (Exception e) {…
}
![Page 10: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/10.jpg)
Exercises1. What is the output produced by the following code?int waitTime = 46;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 11: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/11.jpg)
Exercises2. What is the output produced by the following code?int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 12: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/12.jpg)
Exercises3. What are the throw statements (below)?int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 13: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/13.jpg)
Exercises4. What happens when a throw statement is
executed? This is a general question. Tell what happens in general, not simply what happens in the code below or some other sample code.
int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 14: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/14.jpg)
Exercises5. What is the try block (below)?int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 15: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/15.jpg)
Exercises6. What is the catch block (below)?int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 16: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/16.jpg)
Exercises7. What is the catch block parameter (below)?int waitTime = 12;try {
System.out.println( “Try block entered.” );if (waitTime>30)throw new Exception( “Over 30.” );else if (waitTime<30)throw new Exception( “Under 30.” );elseSystem.out.println( “No exception.” );System.out.println( “Leaving try block.” );
} catch (Exception thrownObject) {System.out.println( thrownObject.getMessage() );
}System.out.println( “After catch block.” );
![Page 17: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/17.jpg)
Exercises8. Is the following legal?
Exception exceptionObject = new Exception( “Oops!” );
![Page 18: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/18.jpg)
Exercises9. Is the following legal?
Exception exceptionObject = new Exception( “Oops!” );
throw exceptionObject;
![Page 19: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/19.jpg)
Try-catch blocks examplesRecall the Integer class (see
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html).What method do we use to convert a String into an
int?What happens if the String does not contain an int?Try it.
What happens when we walk off of the end of an array?Can you avoid this behavior?
![Page 20: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/20.jpg)
Useful exception subclassesArrayIndexOutOfBoundsExceptionNumberFormatExceptionIOExceptionNoSuchMethodExceptionFileNotFoundException
![Page 21: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/21.jpg)
Exercises10. Define an exception class called
PowerFailureException.
The class should have a ctor w/ no parameters. If an exception is thrown with this zero-argument ctor, getMessage should return “Power Failure!”
The class should also have a ctor w/ a single parameter of type String. If an exception is thrown w/ this ctor, then getMessage returns the value that was used as an argument to the ctor.
![Page 22: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/22.jpg)
Exercises11. Define an exception class called
TooMuchStuffException.
The class should have a ctor w/ no parameters. If an exception is thrown with this zero-argument ctor, getMessage should return “Too much stuff!”
The class should also have a ctor w/ a single parameter of type String. If an exception is thrown w/ this ctor, then getMessage returns the value that was used as an argument to the ctor.
![Page 23: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/23.jpg)
Exercises12. Suppose the exception class ExerciseException is defined
as follows:public class ExerciseException extends Exception { public ExerciseException ( ) { super("Exercise Exception thrown!"); System.out.println("Exception thrown."); } public ExerciseException ( String message ) { super(message); System.out.println( "ExerciseException invoked with an
argument."); }}What output would be produced by the following code (which
is just an exercise and not likely to occur in a program)?ExerciseException e = new ExerciseException( “Do be do” );System.out.println( e.getMessage() );
![Page 24: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/24.jpg)
Exercises14. Suppose the exception class MyException is defined as follows:public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); }
public MyException ( String message ) { super("MyException: " + message); }}What output would be produced by the following code?int number;try { System.out.println( “try block entered” ); number = 42; if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” );} catch (MyException exceptionObject) { System.out.println( exceptionObject.getMessage() );}System.out.println( “end of example.” );
![Page 25: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/25.jpg)
Exercises15. Suppose the exception class MyException is defined as follows:public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); }
public MyException ( String message ) { super("MyException: " + message); }}What output would be produced by the following code?int number;try { System.out.println( “try block entered” ); number = 42; if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” );} catch (Exception exceptionObject) { //was MyException System.out.println( exceptionObject.getMessage() );}System.out.println( “end of example.” );
![Page 26: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/26.jpg)
Exercises16. Suppose the exception class MyException is defined as follows:public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); }
public MyException ( String message ) { super("MyException: " + message); }}What output would be produced by the following code?int number;try { System.out.println( “try block entered” ); number = -58; //was 42 if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” );} catch (MyException exceptionObject) { System.out.println( exceptionObject.getMessage() );}System.out.println( “end of example.” );
![Page 27: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/27.jpg)
Multiple catch blocksMore general form of try-catch blocks:try {
…} catch (NegativeNumberException e) {
…} catch (DivisionByZeroException e) {
…}The order of catch blocks is important as they are
evaluated in sequence. So put most specific first.
![Page 28: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/28.jpg)
Exercises19. What output will be produced by the
following code?
public class NegativeNumberException extends Exception{ public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); }
public NegativeNumberException ( String message )
{ super( message ); }}
int n;try { n = 42; if (n > 0) throw new Exception(); else if (n < 0) throw new
NegativeNumberException(); else System.out.println( “bingo!” );} catch (NegativeNumberException e) { System.out.println( “first catch” );} catch (Exception e) { System.out.println( “second catch” );}System.out.println( “end of exercise” );
![Page 29: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/29.jpg)
Exercises20. What output will be produced by the
following code?
public class NegativeNumberException extends Exception{ public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); }
public NegativeNumberException ( String message )
{ super( message ); }}
int n;try { n = -42; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new
NegativeNumberException(); else System.out.println( “bingo!” );} catch (NegativeNumberException e) { System.out.println( “first catch” );} catch (Exception e) { System.out.println( “second catch” );}System.out.println( “end of exercise” );
![Page 30: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/30.jpg)
Exercises21. What output will be produced by the
following code?
public class NegativeNumberException extends Exception{ public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); }
public NegativeNumberException ( String message )
{ super( message ); }}
int n;try { n = 0; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new
NegativeNumberException(); else System.out.println( “bingo!” );} catch (NegativeNumberException e) { System.out.println( “first catch” );} catch (Exception e) { System.out.println( “second catch” );}System.out.println( “end of exercise” );
![Page 31: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/31.jpg)
ExercisesWhat output will be produced by the
following code?
public class NegativeNumberException extends Exception{ public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); }
public NegativeNumberException ( String message )
{ super( message ); }}
int n;try { n = -42; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new
NegativeNumberException(); else System.out.println( “bingo!” );} catch (Exception e) { System.out.println( “first catch” );} catch (NegativeNumberException e)
{ System.out.println( “second catch” );}System.out.println( “end of exercise” );
![Page 32: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/32.jpg)
Throwing exceptions in methods Methods can
throw exceptions, and/or call methods that throw exceptions.
Catch or declare rule: Such a method must then contain a try-catch block (already discussed),
and/or the function heading must specify that the method
may throw an exception. The catch or declare rule is not always enforced.
1. Checked exceptions (descendents of Exception)2. Unchecked exceptions (descendents of
RuntimeException)
![Page 33: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/33.jpg)
Declare (a method that indicates) that an exception may be thrownEx.
public int f ( int x ) throws Exception {…
}
public boolean g ( )throws DivideByZeroException, SomeOtherException
{…
}
![Page 34: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/34.jpg)
Useful methods that may throw exceptionsWhat method can be used to convert strings
to integers?
Open a file for reading (see http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileInputStream.html)
The Scanner class (see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#nextInt())
![Page 35: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/35.jpg)
finally clauseMost general form of try-catch-finally blocks:try {
…} catch (ExceptionClass1 e) {
…} catch (ExceptionClass2 e) {
…} catch (ExceptionClassn e) {
…} finally {
//code executed whether or not an exception was thrown…
}
![Page 36: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/36.jpg)
finally clauseThree cases:
1. no exception occurs in the try block
2. an exception occurs in the try block and is caught
3. an exception occurs in the try block but doesn’t match any catch
![Page 37: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/37.jpg)
Exercisespublic class FinallyDemo { public static void main ( String[] args ) { try { exerciseMethod( 42 ); } catch(Exception e) { System.out.println( "Caught in main.“ ); } }
public static void exerciseMethod ( int n ) throws Exception { try { if (n > 0) throw new Exception( ); else if (n < 0) throw new NegativeNumberException( ); else System.out.println( "No Exception." ); System.out.println( "Still in sampleMethod." ); } catch (NegativeNumberException e) { System.out.println( "Caught in sampleMethod." ); } finally { System.out.println( "In finally block." ); } System.out.println( "After finally block." ); }}
29. What is the output of the following program? What would be the output if the argument to exerciseMethod was -42 instead of 42. How about 0?
![Page 38: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/38.jpg)
Exercises22. What is the output produced by the following program?public class Exercise { public static void main ( String[] args ) { try { System.out.println( "Trying" ); sampleMethod( 98.6 ); System.out.println( "Trying after call." ); } catch(Exception e) { System.out.println( "Catching." ); }
System.out.println( "End program." ); }
public static void sampleMethod ( double test ) throws Exception { System.out.println( "Starting sampleMethod." ); if (test < 100) throw new Exception( ); }}
![Page 39: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/39.jpg)
Exercises23. What is the output produced by the following program?public class Exercise { public static void main ( String[] args ) { try { System.out.println( "Trying" ); sampleMethod( 212 ); //was 98.6 System.out.println( "Trying after call." ); } catch(Exception e) { System.out.println( "Catching." ); }
System.out.println( "End program." ); }
public static void sampleMethod ( double test ) throws Exception { System.out.println( "Starting sampleMethod." ); if (test < 100) throw new Exception( ); }}
![Page 40: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/40.jpg)
Exercises24. Correct the following method definition by
adding a suitable throws clause:
public static void doStuff ( int n ) {if (n<0)throw new Exception( “Negative number.” );
}
25. What happens if an exception is thrown inside a method invocation but the exception is not caught inside the method?
![Page 41: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/41.jpg)
Exercises30. What is the output of the following?import java.util.Scanner;import java.util.InputMismatchException;
public class InputMismatchExceptionDemo { public static void main ( String[] args ) { Scanner keyboard = new Scanner( System.in ); int number = 0; //to keep compiler happy boolean done = false;
while (! done) { try { System.out.println( "Enter a whole number:" ); //number = keyboard.nextInt(); done = true; } catch (InputMismatchException e) { keyboard.nextLine(); System.out.println( "Not a correctly written whole number.“ ); System.out.println( "Try again. " ); } }
System.out.println( "You entered " + number ); }}
![Page 42: Exceptions & exception handling](https://reader036.vdocuments.us/reader036/viewer/2022062814/5681682d550346895dddc744/html5/thumbnails/42.jpg)
Exercisesimport java.util.Scanner;import java.util.InputMismatchException;
public class InputMismatchExceptionDemo { public static void main ( String[] args ) { Scanner keyboard = new Scanner( System.in ); int number = 0; //to keep compiler happy boolean done = false;
while (! done) { try { System.out.println( "Enter a whole number:" ); //number = keyboard.nextInt(); done = true; } catch (InputMismatchException e) { keyboard.nextLine(); System.out.print( "Not a correctly written “); System.out.println( “whole number.“ ); System.out.println( "Try again. " ); } }
System.out.println( "You entered " + number ); }}
31. Give the definition for the following method. Use code similar to this code.
/**
Precondition: keyboard is an object of the class Scanner that has been set up for keyboard input (as we have been doing right along).
Returns: An int value entered at the keyboard. If the user enters an incorrectly formed input she or he is prompted to reenter the value.
*/