Java Exception Handling

The normal flow of a program disrupts when an exception occurs. This stops the Java program and an error message generates. Consider, Exception as an abnormal condition, which needs to be handled, and Exception Handling as a mechanism used to handle it. This includes handling runtime errors like ClassNotFoundException, IOException, RemoteException, etc.

The following errors can occur while running a Java program:

  • Wrong Data as Input
  • Opening a File that does not exist at the same location

Code without Exception Handling

Before moving further, let us run a Java code without handling the exceptions.

class Studyopedia {

  public static void main(String[] args) {
    int[] marks = {90, 95, 88, 80};
    System.out.println(marks[5]);
  }
}

Output

The output displays an error but we are not handling it using try…catch:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
	at Studyopedia.main(Main.java:5)

Now, we will see how to handle the above code with Exception Handling in Java.

Exception Handling in Java

To handle Exceptions, the following concepts are defined in Java:

  • try catch in Java
  • finally in Java
  • throw in Java

Let us learn about them one by one with examples:

try catch in Java

To catch exceptions in Java, use the try…catch pair. The code goes inside both try catch, and is called the protected code. The try block cannot be used alone and is followed by either catch statement or a finally block. Let us see the syntax:

try {
  //  The try block to set the code
}
catch(Exception e) {
  //  The catch block to handle errors
}

Handle Exceptions with try catch

Let us now see an example to handle exceptions in Java with try…catch:

class Studyopedia {

  public static void main(String[] args) {
    
    try {
      int[] marks = {90, 95, 88, 80};
      System.out.println(marks[5]);
    }
    catch (Exception e) {
      System.out.println("Some Issue");  
    }
  }
}

Output

Some Issue

Handle Exceptions with try catch and display the exception

We can also display the exception. Here’s an example:

class Studyopedia {

  public static void main(String[] args) {
    
    try {
      int[] marks = {90, 95, 88, 80};
      System.out.println(marks[5]);
    }
    catch (Exception e) {
      System.out.println("The Exception :" + e);  
    }
  }
}

Output

The Exception :java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4

The above displays the exact error i.e., the elements are 4, but the value is searched for index 5.

Multiple catch blocks in Java

After a try block, we can add more than one catch block. The exception is thrown to the 1st catch block.

Let us see the syntax of the catch block in Java:

try {
   // The try block to set the code
} catch (ExceptionType1 e1) {
   // The catch block to handle errors
} catch (ExceptionType2 e2) {
   // The catch block to handle errors
}

Only one catch block executes since only a single exception occurs at a time. The multiple catch blocks should be ordered accordingly. The catch for ArithmeticException, ArrayIndexOutOfBoundsException, etc. should come before Exception.

Let us see an example. Here, we have set the ArithmeticException and ArrayIndexOutOfBoundsException, but since the error is related to an array out of bound, therefore the catch which gets executed is ArrayIndexOutOfBoundsException:

Class Studyopedia {

  public static void main(String[] args) {
    
    try {
      int[] marks = {90, 95, 88, 80};
      System.out.println(marks[5]);
    }
    catch(ArithmeticException e)  
      {  
        System.out.println("Arithmetic Exception");  
      }    
    catch(ArrayIndexOutOfBoundsException e)  
      {  
        System.out.println("ArrayIndexOutOfBounds Exception");  
      }    
    catch (Exception e) {
      System.out.println("Exception");  
    }
  }
}

Output

ArrayIndexOutOfBounds Exception

finally in Java

The finally in Java executes a code after try catch. Whether the exception is handled or not, the statements in the finally executes. Therefore, add any key code or statement you want to display irrespective of the result inside the finally block. Let us see the syntax of the finally block in Java:

try {
   // The try block to set the code
} catch (ExceptionType1 e1) {
   // The catch block to handle errors
} catch (ExceptionType2 e2) {
   // The catch block to handle errors
} finally {
   // The finally block executes always.
}

Let us see an example of finally in Java:

class Studyopedia {

  public static void main(String[] args) {
    
    try {
      int[] marks = {90, 95, 88, 80};
      System.out.println(marks[5]);
    }
    catch (Exception e) {
      System.out.println("Some Issue");  
    }
    finally {
      System.out.println("The finally executes.");
      System.out.println("The code ends.");
    }
  }
}

Output

Some Issue
The finally executes.
The code ends.

throw keyword in Java

To throw an exception, the throw keyword is used. It throws an exception explicitly. The throw keyword is followed by an exception type, like ArithmeticException, ArrayIndexOutOfBoundsException, SecurityException, etc.

Let us see an example wherein we will throw and error if a student gets less than 50 marks and failed the exam:

class Studyopedia {
  static void verifyMarks(int age) {
    if (age < 50) {
      throw new ArithmeticException("Failed : You must get above 50 to pass the exam.");
    }
    else {
      System.out.println("Congratulations! You passed the exam.");
    }
  }

  public static void main(String[] args) {
    // The marks is less than 50 i.e. student failed the exam
    verifyMarks(45);
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Failed : You must get above 50 to pass the exam.
	at Studyopedia.verifyMarks(Main.java:4)
	at Studyopedia.main(Main.java:13)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java File Handling
Java - User Input
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment