Exception Handling in JAVA

Reading Time: 5 minutes

Introduction to Exception Handling

An exception is a problem that arises during the execution of a program and It can occur for various reasons say-

  • A user has entered an invalid data
  • File not found
  • A network connection has been lost in the middle of communications
  • The JVM has run out of a memory

Exception Handling mechanism follows a flow which is depicted in the below figure, But if an exception is not handled, it may lead to a system failure. That is why handling an exception is very important.

Exception flow-Java Exception Handling -Edureka

Exceptions Hierarchy 

All exception and error types are subclasses of class Throwable, which is the base class of hierarchy. One branch is headed by Error which occurs at run-time and other by Exception that can happen either at compile time or run-time.

Exceptions Hierarchy - Java Exceptions Handling -Edureka

Basically,  an Error is used by the Java run-time system (JVM) to indicate errors that are associated with the run-time environment (JRE). StackOverflowError is an example of such an error. Whereas Exception is used for exceptional conditions that user programs should catch. NullPointerException is an example. 

Now that you know what errors and exceptions are, let’s find out the basic difference between them. Take a look at the below table which draws a clear line between both of them.

 1. Impossible to recover from an error 1. Possible to recover from exceptions
 2. Errors are of type ‘unchecked’ 2. Exceptions can be either ‘checked’ or ‘unchecked’
 3. Occur at runtime 3. Can occur at compile time or run time
 4. Caused by the application running environment 4. Caused by the application itself

Now, we will dive deeper into exceptions and see how they can be handled. First, let’s see the different types of exceptions.

  • Checked Exception
    It’s occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the it or it must specify the exception using throws keyword.
  • Unchecked Exception
    It’s occurs at the time of execution. These are also called Runtime Exceptions. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.

Basic Example of Exceptions

class Exception{
public static void main(String args[]){
//code that may raise exception
catch(Exception e){
// rest of the program

Above code represent an exception wherein inside try block we are going to write a code that may raise an exception and then, that exception will be handled in the catch block.       

Types of Exceptions

1.Built in Exceptions

Built-in ExceptionsDescription
  ArithmeticExceptionIt is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundsExceptionIt is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundExceptionThis exception is raised when we try to access a class whose definition is not found.
FileNotFoundExceptionAn exception that is raised when a file is not accessible or does not open.
IOExceptionIt is thrown when an input-output operation is failed or interrupted.
InterruptedExceptionIt is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
NoSuchFieldExceptionIt is thrown when a class does not contain the field (or variable) specified.
  • User-Defined Exceptions
    Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’.
    Key points to note:
    1. A user-defined exception must extend Exception class.
    2. It is thrown using throw keyword.


class MyException extends Exception{ 
 String str1;
 MyException(String str2) {str1=str2;}
  public String toString(){
   return ("MyException Occurred: "+str1);
class Example1{
public static void main(String args[]){
      System.out.println("Start of try block");
      throw new MyException(“Error Message");
    catch(MyException exp){System.out.println("Catch Block");

Now that you have seen the different types of exceptions, let’s dive deeper into this blog to understand various methods for handling these exceptions.

Exception Handling Methods

How to handle exceptions in Java?  

As I have already mentioned, handling an exception is very important, else it leads to system failure, but how do you handle these exceptions?

Java provides various methods to handle the Exceptions like:

  • try
  • catch
  • finally
  • throw
  • throws

Let’s understand each of these methods in detail.

try block

The try block contains a set of statements where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.

//code that may throw exception
}catch(Exception_class_Name ref){}

Nested try block

try block within a try block is known as nested try block in java.

class Exception{
  public static void main(String args[]){
          System.out.println("going to divide");
          int b=59/0;
         }catch(ArithmeticException e){System.out.println(e);}
          int a[]=new int[5];
        catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
            System.out.println("other statement);
        }catch(Exception e)
         {System.out.println("Exception handeled");}
       System.out.println("casual flow");

catch block

A catch block is where you handle the exceptions. This block must follow the try block and a single try block can have several catch blocks associated with it and you can catch different exceptions in different catch blocks and When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. 

public class Testtrycatch1{
  public static void main(String args[]){
    int data=50/0;//may throw exception
    System.out.println("rest of the code...");

Multi-catch block

If you have to perform various tasks at the occurrence of various exceptions, you can use the multi-catch block.

public class SampleMultipleCatchBlock{
 public static void main(String args[]){
       int a[]=new int[5];
      catch(ArithmeticException e)
        {System.out.println("task1 is completed");}
      catch(ArrayIndexOutOfBoundsException e)
        {System.out.println("task 2 completed");}
      catch(Exception e)
        {System.out.println("task 3 completed");}
      System.out.println("remaining code");

finally block

A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.

class SampleFinallyBlock{
 public static void main(String args[]){
     int data=55/5;
    catch(NullPointerException e)
    finally {System.out.println("finally block is executed");}
    System.out.println("remaining code");

So, this was all about the various methods of handling exceptions.

You might have heard that final, finally and finalize are keywords in Java. Yes, they are, but they differ from each other in various aspects. So, let’s see how final, finally and finalize are different from each other with the help of below table.

final vs finally vs finalize

final finallyfinalize
It is a keyword.It is a block.It is a method.
Used to apply restrictions on class, methods and variables.Used to place an important code.Used to perform clean-up processing just before the object is garbage collected.
final class can’t be inherited, method can’t be overridden & the variable value can’t be changed.It will be executed whether the exception is handled or not.

Similarly, throw & throws sound alike, but they are different from each other,and Let’s see how, with the help of the below table.

throw vs throws 

 1. Used to explicitly throw an exception 1. Used to declare an exception
 2. Checked exceptions cannot be propagated using throw only 2. Checked exceptions can be propagated
 3. Followed by an instance 3. Followed by a class
 4. Used within a method 4. Used with a method signature
 5. Cannot throw multiple exceptions 5. Can declare multiple exceptions
//Java throw example
void a()
  throw new ArithmeticException("Incorrect");
//Java throws example
void a()throws ArithmeticException
  //method code
//Java throw and throws example
void a()throws ArithmeticException
  throw new ArithmeticException("Incorrect");

Finally this brings us to the end of our blog on Exception Handling in Java. I hope you found this blog informative and added value to your knowledge.

Written by 

Deepak kumar is a Software Intern at Knoldus Inc. He has done Post Graduation from Ajay Kumar Garg Engineering College Ghaziabad. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is a quick learner, problem solver and always enjoy to help others. His hobbies playing Cricket and watching Hollywood movies.

1 thought on “Exception Handling in JAVA8 min read

Comments are closed.