What is the difference between throw e and throw new Exception(e) in catch block in java?

Java 8Object Oriented ProgrammingProgramming

An exception is an issue (run time error) occurred during the execution of a program. Here are some example scenarios −

  • If you have an array of size 10 if a line in your code tries to access the 11th element in this array.
  • If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to valuate it).

When exception occurs the program terminates abruptly at the line that caused exception, leaving the remaining part of the program unexecuted. To prevent this, you need to handle exceptions.

There are two types of exceptions in java.

  • Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
  • Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.

Handling exception

To handle exceptions Java provides a try-catch block mechanism.

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.

Syntax

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in the try block, the catch block (or blocks) that follows the try is verified.

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.

Example

import java.io.File;
import java.io.FileInputStream;
public class Test {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         File file =new File("my_file");
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}

Output

Given file path is not found

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

In the following Java example our code in demoMethod() might throw ArrayIndexOutOfBoundsException and ArithmeticException. We are catching these two exceptions in two different catch blocks.

In the catch blocks we are re-throwing both exceptions one by wrapping within higher exception and the other one directly.

import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
   public void demoMethod() {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         throw new IndexOutOfBoundsException();
      }catch(ArithmeticException e) {
         throw e;
      }
   }
   public static void main(String [] args) {
      new RethrowExample().demoMethod();
   }
}

Output

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4

Exception in thread "main" java.lang.ArithmeticException: / by zero
   at myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
   at myPackage.RethrowExample.main(RethrowExample.java:25)

Output

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
   at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
   at myPackage.RethrowExample.main(RethrowExample.java:23)
raja
Published on 06-Aug-2019 09:15:36
Advertisements