Can we to override a catch block in java?


Description

When a piece of code in particular method throws an exception, and is handled using try-catch pair. If we are calling this method from another one and, the calling line is wrapped within try-catch pair. Now, how can I override the catch block by the catch block of the calling method.

When a piece of code in a method throws an exception (compile time) we must either handle it by wrapping it within the try-catch pair or, throw it (postpone) to the calling method using the throws keyword else a compile time error occurs.

In the following Java example the code in the readFile() method generates a FileNotFoundException and we are not handling it.

Example

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      sb.append(sc.next());
      data = sb.toString();
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

Compile time error

On compiling, the above program generates the following compile time error.

ExceptionExample.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
         Scanner sc = new Scanner(new File("E://test//sample.txt"));
                                  ^
1 error

To resolve this error we need to either handle the exception using try-catch pair as −

Example

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
         try {
            Scanner sc = new Scanner(new File("E://test//sample.txt"));
            String input;
            StringBuffer sb = new StringBuffer();
            sb.append(sc.next());
            data = sb.toString();
         } catch (FileNotFoundException ex) {
            System.out.println("exception occurred");
         }
         return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

Output

exception occurred

Or, throw it using the throws keyword. If you do so, the exception is postponed to the calling line of this this method i.e. error occurs at that line now.

Example

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path)throws FileNotFoundException {
      String data = null;
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      sb.append(sc.next());
      data = sb.toString();
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

Compile time error

ExceptionExample.java:17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      readFile(path);
               ^
1 error

To resolve this you need to either wrap the calling line or throw the exception again using the throws keyword.

public static void main(String args[]) {
   String path = "E://test//sample.txt";
   OverridingException obj = new OverridingException();
   try {
      readFile(path);
   }catch(Exception ex) {
      System.out.println("Exception occured");
   }
}

That being said, if you handle the exception using try-catch pair in the source method (the method that generates the exception originally) there is no need to handle it again in the calling method. Having try-catch in both places is pointless.

The only way to execute the content in the both catch blocks is to re-throw the exception.

Re-throwing exceptions

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).

While re-throwing exceptions you can throw the same exception as it is without adjusting it as

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
} catch(ArithmeticException e) {
   throw e;
}

Or, wrap it within a new exception and throw it. When you wrap a cached exception with in another exception and throw it, it is known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing higher level of exception maintaining the abstraction.

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
} catch(ArrayIndexOutOfBoundsException e) {
   throw new IndexOutOfBoundsException();
}

Example

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
         try {
            Scanner sc = new Scanner(new File("E://test//sample.txt"));
            String input;
            StringBuffer sb = new StringBuffer();
            sb.append(sc.next());
            data = sb.toString();
         }catch (FileNotFoundException ex){
            System.out.println("Exception occurred: source method");
         throw ex;
      }
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
         try {
            readFile(path);
         }catch(Exception ex) {
            System.out.println("Exception occurred: calling method");
      }
   }
}

Output

Exception occurred: source method
Exception occurred: calling method

Updated on: 12-Sep-2019

739 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements