Java Reference
In-Depth Information
Self-Test Exercises (continued)
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.");
}
}
extra code
on website
The class FinallyDemo is on the website 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. This 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
 
Search WWH ::




Custom Search