Java Reference
In-Depth Information
A method can use the syntax throws . This means that instead of handling the
exception, the method passes the exception to the calling method. As a result, it will
be the job of the calling method to handle the exception.
The third rewrite is very clever. The getNumber method only returns a single piece of
data. However, when the getNumber method does not raise an exception, the line repeat =
false is executed and the while loop is terminated. Now there is no need to send an array
to the getNumber method. If the user does not enter an integer, then the catch block does
nothing and the block of the while loop needs to be repeated.
Note that we can rewrite the code for the getNumber method as follows.
public static int getNumber () throws
{
However, since the InputMismatchException class inherits from the Exception class,
both versions are fine. If we write throws Exception , this means that the getNumber
method will now handle any type of exception and will throw it back to the originating
method. Alternatively, the code throws InputMismatchException means that the method
will only throw back to the calling method an exceptions of type InputMismatchException .
If the method generates an unchecked exception of a different type, for example as a result
of dividing by 0, then the program will crash. If we want to specify that a method handles
exceptions of several types, then we can separate the exception classes by commas.
InputMismatchException
We need to be careful when we write code that can raise exceptions. If a method
in your program raises an unchecked exception and the exception is not handled, then
the program will crash and the stack trace will be printed. Alternatively, code that
generates a checked exception that is not handled will simply not compile.
Although similar to an if - else statement, a try - catch - finally block acts in a much
different fashion. Let us consider the following example method.
public static int f( int n) {
int r=0;
try {
r= n n;
return r;
finally
{
if ( n==2) return r+1;
}
} The obvious question is what will be returned by the method when n=2 . The secret
to answering the question is knowing that the finally block is always executed. Therefore,
thecodehastwo return statements! The return statement in the try block will return 4,
while the return statement in the finally block will return 5. It turns out that the method
will return 5 because the second return statement is the last one to be executed.
Thecodeinthe finally block will always be executed. If there is a return state-
ment in the finally block, then the method will rely on this statement to compute
the return value. The only way to skip executing the finally block is to directly exit
the program before that by writing System.exit(0) . The last command terminates
the program with exit code 0.
 
Search WWH ::




Custom Search