Exception Handling in Java

1. Introduction

An exception is a condition that is caused by run-time error in a program. When java Interpreter catches an error such as divide by zero the interpreter creates exception object and throws it to JVM(Java Virtual Machine). A Java exception is an object that describes an exceptional condition that occurred in the code. The exception handling mechanism actually provides a means to detect and report an exceptional condition, so that corrective action can be taken, listing out the steps as:

  1. Find the problem i.e. hit the exception
  2. Inform that error has occurred i.e. throws the exception.
  3. Receives the error information i.e. catch the exception.
  4. Take corrective action so that handle the exception.

2. Types of Exceptions in Java

Understand how exception handling works in Java, you need to understand the three categories of exceptions:

  • Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be seen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

3. Exception Hierarchy

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error, which is derived from the Throwable class.

Errors are not normally trapped from the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors. Here is a list of most common checked and unchecked Java’s Built-in Exceptions.


Exception Hierarchy

4. Catching Exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

5. Practical exception scenario explained

5.1 With single catch block

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

This would produce following result:

5.2 With multiple catch blocks

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

5.3 The throws/throw keywords

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.

5.4 The finally keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code or inside the try block.

A finally block appears at the end of the catch blocks and has the following syntax:

5.4.1 Example

This would produce following result:

6. How do the Exceptions propagate?

Whenever there is some exception, the runtime system starts searching for the handlers. So there might be nested method calls from the controllers to the delegate to the service layer to the DAO layer, and so on. Suppose that there was some exception in some method of the DAO class. What the runtime system does, it starts checking the methods in the call stack in the reverse order, one after the other, to find if there exists any code to handle this exception. This piece of code that handles the exception is something what we call as the the exception handler. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.