Java Reference
In-Depth Information
Note that a catch block's declaration is exactly like a method declaration. It starts with the keyword catch , followed
by a pair of parentheses. Within the parentheses, you declare a parameter, as you do in a method. The parameter type
is the name of the exception class that it is supposed to catch. The parameterName is a user-given name. Parentheses
are followed by an opening brace and a closing brace. The exception handling code is placed within the braces.
When an exception is thrown, the reference of the exception object is copied to the parameterName . You can use the
parameterName to get information from the exception object. It behaves exactly like a formal parameter of a method.
You can associate one or more catch blocks to a try block. The general syntax for a try-catch block is as follows.
The following snippet of code shows a try block, which has three catch blocks associated with it. You can associate as
many catch blocks to a try block as you want.
try {
// Your code that may throw an exception goes here
}
catch (ExceptionClass1 e1){
// Handle exception of ExceptionClass1 type
}
catch (ExceptionClass2 e2){
// Handle exception of ExceptionClass2 type
}
catch (ExceptionClass3 e3){
// Handle exception of ExceptionClass3 type
}
Let's use a try-catch block to handle the possible divide by zero exception in your code. Listing 9-2 has the
complete code.
Listing 9-2. Handling an Exception Using a try-catch Block
// DivideByZeroWithTryCatch.java
package com.jdojo.exception;
public class DivideByZeroWithTryCatch {
public static void main(String[] args) {
int x = 10, y = 0, z;
try {
z = x / y;
System.out.println("z = " + z);
}
catch(ArithmeticException e) {
// Get the description of the exception
String msg = e.getMessage();
// Print a custom error message
System.out.println("An error has occurred. The error is: " + msg);
}
System.out.println("At the end of the program.");
}
}
An exception has occurred. The error is: / by zero
At the end of the program.
Search WWH ::




Custom Search