-
If a program does not handle exceptions at all, it will stop the program and produce a message that describes the exception and where it happened. This information can be used to help track down the cause of a problem.
- The code shown below throws an
ArithmeticException
when the program tries to divide by zero. The program crashes and prints out information about the exception:
int numerator = 23;
int denominator = 0;
// the following line produces an ArithmeticException
System.out.println(numerator/denominator);
System.out.println("This text will not print");
Run Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByZero.java:10)
The first line of the output tells which exception was thrown and gives some information about why it was thrown. “DivideByZero.main” indicates that the exception occurred in the main method of the DivideByZero class. In the parentheses, the specific file name and line number are given so that the programmer can find where their code went wrong (in the example above, the exception occurred on line 10 of a Java file, DivideByZero.java). This is the line where Java found a problem. The actual root cause of the problem may be a line or two ahead of line 10.
The rest of the output tells where the exception occurred and is referred to as a call stack trace. In this case, there is only one line in the call stack trace, but there could be several, depending on where the exception originated.
- When exceptions are handled by a program, it is possible to obtain information about an exception by referring to the “exception object” that Java creates in response to an exception condition. Every exception object contains a String that can be accessed using the
getMessage
method as follows:
try{
quotient = numerator/denominator;
System.out.println("The answer is: " + quotient);
} catch (ArithmeticException e){
System.out.println(e.getMessage());
}
If a divide by zero error occurs, an exception is thrown and the following message is displayed:
/ by zero
-
Printing the value returned by getMessage
can be useful in situations where we are unsure of the type of error or its cause.
- If an exception is unknown by your Java class, you may need to import the appropriate exception (just like you would import any other class you wanted your class to know about). For example, the
ArithmeticException
is a standard Java class and no import statement is needed for it. However, IOException
is part of the java.io
package and must therefore be imported before it is used.