img
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Displaying a Description of an Exception
Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception. You can display this description in a println( )
statement by simply passing the exception as an argument. For example, the catch block
in the preceding program can be rewritten like this:
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each divide-by-
zero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero
While it is of no particular value in this context, the ability to display a description of
an exception is valuable in other circumstances--particularly when you are experimenting
with exceptions or when you are debugging.
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch
block. The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home