Java Reference
In-Depth Information
Self-Test Exercises (continued)
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.");
}
}
extra code
on CD
The class FinallyDemo is on the CD that comes with this text.
Rethrowing an Exception
A catch block can contain code that throws an exception. In rare cases you may find it
useful to catch an exception and then, depending on the string produced by getMessage
or depending on something else, decide to throw the same or a different exception for
handling further up the chain of exception handling blocks.
The AssertionError Class
When we discussed the assert operator and assertion checking in Chapter 3, we said that
if your program contains an assertion check and the assertion check fails, your program
will end with an error message. That statement is more or less true, but it is incomplete.
What happens is that an object of the class AssertionError is thrown. If it is not caught
in a catch block, your program ends with an error message. However, if you wish, you
can catch it in a catch block, although that is not a very common thing to do. The
AssertionError class is in the java.lang package and so requires no import statement.
As the name suggests, the class AssertionError is derived from the class Error , so
you are not required to either catch it in a catch block or declare it in a throws clause.
Exception Handling with the Scanner Class
When reading int values from the keyboard, we have been using the nextInt method of
the Scanner class. We said that if the user enters something other than a well-formed int
value, then your program will end with an error message. That's true as far as it goes, but
the full detail is that if the user enters something other than a well-formed int value, an
exception of type InputMismatchException will be thrown. If the exception is not
caught, your program ends with an error message. However, you can catch the exception,
Search WWH ::




Custom Search