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 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.
Last modified: December 12, 2022
Back to Handling Exceptions