Title: Chapter 9 Exception Handling
1Chapter 9Exception Handling
2Exceptions 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). - Handle the possibility that an exception may be
thrown.
31. Define a new exception class
- extend Exception (or extend a subclass of
Exception) - See http//java.sun.com/j2se/1.5.0/docs/api/java/l
ang/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.
4Define a new exception class example
- //typical sample code
- public class DivisionByZeroException extends
Exception - public DivisionByZeroException ( )
- super( Division by zero! )
-
- public DivisionByZeroException ( String message
) - super( message )
-
5Define 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
-
62. Create an exception instance
- Ex.
- new Exception( Uh oh! )
- Exception e new Exception( Rats! )
73. Throw an exception
- Ex.
- throw new Exception( Invalid value. )
- Exception e new Exception( Invalid age. )
- throw e
84. Declare (a method that indicates) that an
exception may be thrown
- Ex.
- public int f ( int x ) throws Exception
-
95. Handle the possibility that an exception may
be thrown
- The try-catch blocks
- try
-
- catch (Exception e)
-
-
10Exercises
- 1. What is the output produced by the following
code? - int waitTime 46
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
11Exercises
- 2. What is the output produced by the following
code? - int waitTime 12
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
12Exercises
- 3. What are the throw statements (below)?
- int waitTime 12
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
13Exercises
- 4. 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 (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
14Exercises
- 5. What is the try block (below)?
- int waitTime 12
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
15Exercises
- 6. What is the catch block (below)?
- int waitTime 12
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
16Exercises
- 7. What is the catch block parameter (below)?
- int waitTime 12
- try
- System.out.println( Try block entered. )
- if (waitTimegt30)
- throw new Exception( Over 30. )
- else if (waitTimelt30)
- throw new Exception( Under 30. )
- else
- System.out.println( No exception. )
- System.out.println( Leaving try block. )
- catch (Exception thrownObject)
- System.out.println( thrownObject.getMessage() )
-
- System.out.println( After catch block. )
17Exercises
- 8. Is the following legal?
- Exception exceptionObject new Exception(
Oops! )
18Exercises
- 9. Is the following legal?
- Exception exceptionObject new Exception(
Oops! ) - throw exceptionObject
19Try-catch blocks examples
- Recall 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?
20Useful exception subclasses
- ArrayIndexOutOfBoundsException
- NumberFormatException
- IOException
- NoSuchMethodException
- FileNotFoundException
21Exercises
- 10. 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.
22Exercises
- 11. 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.
23Exercises
- 12. 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() )
24Exercises
- 14. 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 (numbergt0)
- throw new MyException( Hi Mom! )
- System.out.println( leaving try block )
- catch (MyException exceptionObject)
25Exercises
- 15. 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 (numbergt0)
- throw new MyException( Hi Mom! )
- System.out.println( leaving try block )
- catch (Exception exceptionObject) //was
MyException
26Exercises
- 16. 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 (numbergt0)
- throw new MyException( Hi Mom! )
- System.out.println( leaving try block )
- catch (MyException exceptionObject)
27Multiple catch blocks
- More 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.
28Exercises
- 19. 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 gt 0)
- throw new Exception()
- else if (n lt 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 )
29Exercises
- 20. 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 gt 0)
- throw new Exception()
- else if (n lt 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 )
30Exercises
- 21. 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 gt 0)
- throw new Exception()
- else if (n lt 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 )
31Exercises
- 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 gt 0)
- throw new Exception()
- else if (n lt 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 )
32Throwing 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.
- Checked exceptions (descendents of Exception)
- Unchecked exceptions (descendents of
RuntimeException)
33Declare (a method that indicates) that an
exception may be thrown
- Ex.
- public int f ( int x ) throws Exception
-
-
- public boolean g ( )
- throws DivideByZeroException, SomeOtherException
-
-
-
34Useful methods that may throw exceptions
- What method can be used to convert strings to
integers? - Open a file for reading (see http//java.sun.com/j
2se/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.htmlnextInt())
35finally clause
- Most 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 -
36finally clause
- Three cases
- no exception occurs in the try block
- an exception occurs in the try block and is
caught - an exception occurs in the try block but doesnt
match any catch
37Exercises
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?
- public 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 gt 0)
- throw new Exception( )
- else if (n lt 0)
- throw new NegativeNumberException(
) - else
- System.out.println( "No
Exception." ) - System.out.println( "Still in
sampleMethod." ) - catch (NegativeNumberException e)
38Exercises
- 22. 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 lt 100)
- throw new Exception( )
-
39Exercises
- 23. 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 lt 100)
- throw new Exception( )
-
40Exercises
- 24. Correct the following method definition by
adding a suitable throws clause - public static void doStuff ( int n )
- if (nlt0)
- 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?
41Exercises
- 30. 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.
" )
42Exercises
- 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.print( "Not a
correctly written ) - System.out.println( whole
number. ) - System.out.println( "Try again.
" )
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. /
43/ Chapter 9 question 1 Question1Average.java
This program calculates the average of N
numbers and throws an exception if a negative
number is entered for N. If any exception
occurs while entering a number, the user will be
prompted for the number again. / import
java.util.Scannerpublic class
Question1Average public static void
main(String args) // Variable
declarations Scanner scan new
Scanner(System.in) int n 0 int sum 0
double average boolean error
44 // Loop until there is no error do
try error false // Assume no
error System.out.println("How many numbers do
you want
to enter?") n scan.nextInt() if (n
lt 0 ) throw new Exception("Number must
be greater than 0.") //end try catch
(Exception e) // Catch any exception and print
// the error message error
true System.out.println(e.getMessage())
//end catch while (error)
45// Loop through each number and calculate the
average for (int i0 iltn i) //
Repeat input as long as there is an
error do try error false //
Assume no error System.out.println("Enter
number " (i1)) int num
scan.nextInt() sum num catch
(Exception e) // Set error flag if an
exception occurs error true
System.out.println("Error, please enter the
number again.") // Read newLine
remaining from nextInt String temp
scan.nextLine() while (error)
// end for average (double) sum / n
System.out.println("\nThe average is "
average) //end main // Question1Average