Throw and throws in Java

Java 8Object Oriented ProgrammingProgramming

The throws keyword

Whenever an exception occurs in a method you need to handle it by wrapping the code that caused exception within the try-catch block or, you can throw/postpone it using to the calling method using the throws keyword. Then you need to handle the exception at the calling method.

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

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

The throw keyword

You can throw a user-defined exception or, a predefined exception explicitly using the throw keyword.

There are two types of exceptions user-defined and predefined each exception is represented by a class and which inherits the Throwable class.

To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.

Example

Following Java program throws a NullPointerException

 Live Demo

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

Output

Hello
Exception in thread "main" java.lang.NullPointerException
   at July_set2.ExceptionExample.main(ExceptionExample.java:6)

Whenever you throw an exception explicitly you need to make sure that the line with throw keyword is the last line of the program. This is because any code written after it is unreachable code and if you still have code snippets below this line a compile-time error will be generated.

Example

 Live Demo

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
      System.out.println("How are you");
   }
}

Output

Compile-time error

D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
   System.out.println("How are you");
   ^
1 error

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- ing 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 within another exception and throw it, it is known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing a 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 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 exceptions 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)
raja
Published on 06-Sep-2019 15:37:45
Advertisements