Exception Handling in Java

The Java programming language uses exceptions to handle errors and other exceptional events.

What is an Exception:

An exception is an event that interrupts the normal flow of the program’s instructions. Exceptions occur during the execution of a program and terminates the program. As mentioned earlier, the Java language uses exceptions to handle errors and other exceptional events.

When an error occurs within a method, the method creates an object (i.e., exception object) and hands it off to the runtime system. This exception object contains the information about the error. This process of creating an exception object and handling it to the runtime system is called throwing an exception. Whenever a method throws an exception, the runtime system tries to find some exception handler to handle the exception. In this process of handling an exception we have to provide a user friendly message which can be easily understandable to a user rather then simply throwing system generating message which is hard for a non-technical person to understand.

Let me show you a sample system generated message.

Output:

The main purpose of exception handling is to continue the flow of the program.

Types of Exceptions:

There are two types of exceptions:

1. Checked Exceptions
2. Unchecked Exceptions

1. Checked Exception:

Checked exceptions occur at the compile time. These are aka Compile Time Exceptions. As a programmer we have to handle these exceptions at the time of compilation.

Let’s see an example:

Output:

Let’s see how to handle this.

Using throws keyword:

Using try catch block:

Some of the checked exceptions are as follows:

  • IOException
  • ClassNotFoundException
  • SQLException

2. Unchecked Exception:

Unchecked exceptions occur at the time of execution. These are aka Runtime Exceptions. As a programmer we have to judge it in advance and handle them properly.

Let’s see an example:

Output:

Handling the exception:

Output:

Some of the unchecked exceptions are as follows:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException

Must Read: Java Tutorial

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.

Rajkumar

Leave a Comment

Share via
Copy link
Powered by Social Snap