Is it possible to throw exception without using "throws Exception" in java?


When an exception occurs in Java, the program terminates abnormally and the code past the line that caused the exception doesn’t get executed.

To resolve this you need to either wrap the code that causes the exception within try catch ot, throw the exception using the throws clause. If you throw the exception using throws clause it will be p[postponed to the calling line i.e.

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);
   }
}

Output

Compile-time error

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

Without using throws

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). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.

Example

In the following Java example our code in demo method() might throw ArrayIndexOutOfBoundsException an 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 the higher exception and the other one directly.

 Live Demo

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();
   }
}

Output1

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)

Output2

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)

Updated on: 06-Sep-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements