Java Reference
In-Depth Information
When we talk about throwing an exception, we are talking about three things.
Occurrence of an exceptional condition
Creation of a Java object to represent the exceptional condition
Throwing (or passing) the exception object to the exception handler
The throwing of an exception is the same as passing an object reference to a method. Here, you may imagine the
exception handler as a method that accepts a reference of an exception object. The exception handler catches the
exception object and takes appropriate action. You can think of catching an exception by the exception handler as a
method call without the return, where the exception object's reference is the actual parameter to the method. Java
also lets you create your own object that represents an exception and then throw it.
Tip
an exception in Java is an object that encapsulates the details of an error.
Using a try-catch Block
Before I discuss the try-catch block, let's write a Java program that attempts to divide an integer by zero, as
shown in Listing 9-1.
Listing 9-1. A Java Program Attempting to Divide an Integer by Zero
// DivideByZero.java
package com.jdojo.exception;
public class DivideByZero {
public static void main(String[] args) {
int x = 10, y = 0, z;
z = x/y;
System.out.println("z = " + z);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.jdojo.exception.DivideByZero.main(DivideByZero.java:7)
Is the output of Listing 9-1 what you were expecting? It indicates an exception has occurred when you ran the
DivideByZero class. The output contains four pieces of information:
It includes the name of the thread in which the exception occurred. The name of the thread
is “main”. You can learn about threads and the name of a thread in detail in the chapter on
threads in the topic Beginning Java Language Features (ISBN 978-1-4302-6658-7).
It includes the type of the exception that has occurred. The type of an exception is indicated by
the name of the class of the exception object. In this case, java.lang.ArithmeticException
is the name of the class of the exception. The Java runtime creates an object of this class and
passes its reference to the exception handler.
It includes a message that describes the exceptional condition in the code that caused the
error. In this case, the message is “/ by zero” (read “divide by zero”).
 
 
Search WWH ::




Custom Search