Java Exception Handling

In Java, an exception is an unnatural condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

In those computer languages which don't support the exception handling, then the errors must be checked and handled manually.

Exception handling in Java, brings run-time error management into the object-oriented world.

In Java exception is an object which describes an exceptional (i.e., error) condition that has occurred in a piece of code.

What if an exception arises ?

When an exceptional condition arises, then an object representing that exception is created and thrown in the method that caused the error. That method might choose to handle the exception itself, or pass it on. Either way, at several point, the exception is caught and processed.

How exception can be generated ?

Exceptions can be generated through the Java's run-time system, or they can be generated by your code manually.

Exceptions thrown by Java, relate to the fundamental errors that violate the Java language's rules or the constraints of the execution environment of Java. Manually generated exceptions are generally used to report some error condition to the caller of a method.

How exception can be manage ?

Java's exception handling is managed via the following five keywords :

  1. try
  2. catch
  3. throw
  4. throws
  5. finally

Program statements which you want to monitor for exceptions are contained within the try block. If an exception occurs inside a try block, it is thrown. Your code can catch this exceptions using the catch and handle it in some rational manner. The System-generated exceptions are automatically thrown by the Java's run-time system. To manually throw an exception, use the throw keyword. Any exception that is thrown out of a method must be specified as such by the throws clause. Any code that must be executed after a try block completes is put in a finally block.

Java Exception Handling Syntax

Here is the general form of Java exception handling block :

try {
   // block of the code to monitor for the errors
   
} catch(ExceptionType1 exObj) {
   // exception handler for ExceptionType1
   
} catch(ExceptionType2 exObj) {
   // exception handler for ExceptionType2
}
// ...
finally {
   // block of the code to be executed after try block ends
}

Here, ExceptionType is the type of exception that has occurred.

Java Exception Types

All the exception types are subclasses of the Throwable built-in class. Therefore, Throwable is at the top of the exception class hierarchy. Just below Throwable are two subclasses that partition exceptions into the two distinct branches. One branch is headed by Exception. This class is used for the exceptional conditions that user programs should catch. This is also the class which you will subclass in creating your own custom exception types. There is an important subclass of Exception, called the RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include the things like division by zero and invalid array indexing.

The other branch is topped by Error, which defines exceptions that are not expected to be caught under the normal circumstances by your program. Exceptions of the type Error are used by Java's run-time system to indicate the errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. We will not deal with exceptions of the type Error, because these are typically created in response to ruinous failures that cannot usually be handled by your program.

The top-level exception hierarchy is shown in this figure :

java exception handling

Java Uncaught Exceptions

Before you learn about how to handle exceptions in your Java program, it is useful to see what happens when you don't handle them. Here below small program includes an expression that intentionally causes a divide-by-zero error :

class Excp0 {
   public static void main(String args[]) {
      int denom = 0, num = 52;
      int res = num / denom;
   }
}

When Java's run-time system detects the attempt to divide by zero, this constructs a new exception object and then throws this exception. This cause the execution of the Excp0 to stop, as once an exception has been thrown, it must be caught through an exception handler and dealt with immediately. In this example, we have not supplied any exception handlers of our own, therefore the exception is caught by the default handler that is provided by the Java's run-time system.

Any exception that is not caught by your program will finally be processed by the default handler. The default handler displays a string describing the exception, prints stack trace from the point at which the exception occurred, and terminates the program.

Below is the exception generated when this example is executed :

java.lang.ArithmeticException: / by zero
   at Excp0.main(Excp0.java:4)

Notice here that how the class name, Excp0,
the method name, main,
the filename, Excp0.java,
and the line number, 4,
are all included in simple stack trace. Also notice here that the type of exception thrown is a subclass of Exception called ArithmeticException, which more especially describes what type of error happened.

The stack trace will always show the sequence of the method invocations which led up to the error. For instance, here is another version of the preceding program that simply introduces the same error but in a method separate from the main():

class Excp1 {
   static void dividemethod() {
      int denom = 0, num = 20;
      int res = num / denom;
   }
   public static void main(String args[]) {
      Excp1.dividemethod();
   }
}

The resulting stack trace from the default exception handler shows that how the entire call stack is displayed :

java.lang.ArithmeticException: / by zero
   at Excp1.dividemethod(Excp1.java:4)
   at Excp1.main(Excp1.java:7)

As you can see, the bottom of the stack is main's line 7, that is the call to the method named dividemethod(), which caused the exception at line 4. The call stack is quite useful for the debugging purpose, because it pinpoints the precise sequence of steps that led to the error.

Java Online Test


« Previous Tutorial Next Tutorial »