Java throw and throws Keyword


JavaViews 1741

We can handle exceptions in different ways in Java. In the previous tutorial, we have seen how to handle the exception using the try-catch block. In this tutorial, we will learn about handling exceptions using java throw and throws keyword.

Java throw keyword

In previous tutorials, we have seen how to handle built-in exceptions like ArithmeticException(to handle divide by 0 error), ArrayIndexOutOfBounds(to handle array index issues), etc. Similarly, we can define our own rules to throw an exception for a certain condition using the java throw keyword. We can handle these special conditions using the existing Exception class(ArithmeticException, NullPointerException, NumberFormatException, etc).

Syntax

throw new excpetion_class("Exception message");

throw – java keyword to throw an exception

new – java keyword to create a new exception

exception_class  – may be any of the existing defined exception classes.

Exception message – the custom message regarding the unexpected condition or exception

Example

In the below example, we are creating a new condition for an exception where it does not allow a person with age > 60. In this case, we generate an ArithmeticException type using the java throw keyword and print a custom message “Senior citizens are not allowed”.

public class ThrowExample {

  int age;
  public static void display(int age) {
    if(age>60)
      throw new ArithmeticException("Senior citizens are not allowed");
    else
      System.out.println("Person with age: " + age + " is allowed");
  }
  
  public static void main(String[] args) {
    display(65);
  }

}
Exception in thread "main" java.lang.ArithmeticException: Senior citizens are not allowed
  at ThrowExample.display(ThrowExample.java:6)
  at ThrowExample.main(ThrowExample.java:12)

Once it throws an exception, then it does not execute the remaining statements. For example, if we have another method call with a different value, it will not execute that method. This means it will not execute the statement display(45)  since the previous statement has produced an exception.

public static void main(String[] args) {
    display(65);
    display(45);
  }

Java throws keyword

Throws keyword in Java is another way to handle the exception. We use the throws keyword in the method declaration to show that there are possibilities for the method to produce exceptions. We can use throws to handle both checked and unchecked exceptions.

Syntax

Below is the syntax of using the throws keyword. It is important to handle the exception using the try-catch from where we call the method. Else it will throw compilation error.

class class_name{
  static void method_name() throws ExceptionType{
    
  }
  
  public static void main(String[] args) {
    try {
      method_name();
    }
    catch(ExceptionType e) {
      
    }
  }
}

The throws clause is similar to the try-catch block which we have learned in the previous tutorial. The main use of throws is when we have several methods throwing an exception, it would be difficult to handle each using the try-catch. Hence we can use throws in the method declaration and handle the exceptions using the try-catch block from where we call the method. This is another advantage where it forces to implement exception handling from where the method is called.

Let us understand this with an example.

Example of unchecked exceptions

Below is an example of using the throws keyword to handle the exception. We need to throw the exception in the method declaration by mentioning the exception type and then handle the exception using try-catch in the method call. In this way, we give the responsibility of exception handling to the method caller.

public class ThrowsDemo {

  static void display() throws ArithmeticException {
    int result = 10/0;
    System.out.println("Result:" + result);
  }
  
  
  public static void main(String[] args) {
    try {
      display();
    }
    catch(ArithmeticException e) {
      System.out.println("Exception: " + e.getMessage());
    }
    
    System.out.println("Exceptions example");

  }

}
Exception: / by zero
Exceptions example

Example of checked exceptions

Below is an example of handling checked exceptions using the throws keyword. In this example, we have given an incorrect file name. Hence when it executes the statement File f = new File(filename) it throws IOException specific to FileNotFound.

import java.io.*;


public class ThrowsExample {

  public static void readFile() throws IOException {
    String filename = "E:\\CheckedExceptions.txt";
    int i;
    File f = new File(filename);
    FileReader fr = new FileReader(f);
    
  }
  public static void main(String[] args) {
    try {
      readFile();
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }

  }

}
E:\CheckedExceptions.txt (The system cannot find the file specified)

Handling Multiple exceptions using throws

We can handle multiple exceptions using the throws keyword by separating each type using a comma separator(,) in the method signature.

This example shows how you can handle IOException and ClassNotFoundException using the throws keyword.

public class MultiExceptions {

  static void showData() throws IOException,ClassNotFoundException{
    //code that may generate exception
      
  }
  public static void main(String[] args) {
    try {
      showData();
    }
    catch(IOException e) {
      System.out.println("Exception: " + e.getMessage());
    }
    catch(ClassNotFoundException e) {
      System.out.println("Exception: " + e.getMessage());
    }
  }

}

Example: Using throw and throws

We can use both throw and throws keyword to handle exceptions in Java. We use the throws keyword in the method declaration and throw a new exception inside using the throw keyword. It throws a new exception when it satisfies the condition age > 60.

public class MultiExceptions {

  static void showData(int age) throws ArithmeticException {
    if(age > 60)
      throw new ArithmeticException("Senior citizen not allowed");
    else
      System.out.println("Age: " + age);	
  }
  public static void main(String[] args) {
    try {
      showData(70);
    }
    catch(ArithmeticException e) {
      System.out.println("Exception: Division by 0 not allowed");
    }
    
  }

}
Exception: Division by 0 not allowed

There is an important point to note while using throw to create a new exception related to checked exception. We cannot use the throw keyword alone. It forces us to declare the exception type in the method declaration using the throws keyword. If we do not use it then it will result in a compilation error.

Java Throws keyword

Below is the correct way to use the throw keyword if required for checked exceptions. Generally, it is best practice to use throws or try-catch for checked exception handling.

import java.io.FileNotFoundException;

public class ExceptionDemo {

  public static void print() throws FileNotFoundException {
    throw new FileNotFoundException("File not found");
  }
  public static void main(String[] args) {
    try {
      print();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

}
java.io.FileNotFoundException: File not found
  at ExceptionDemo.print(ExceptionDemo.java:6)
  at ExceptionDemo.main(ExceptionDemo.java:10)

Difference between throw and throws keyword

Java throwJava throws
Used inside the methodUsed in method declaration
It is used to throw a new exception inside the methodIt is used to declare an exception that might occur inside the method
We can throw only single exception at a timeWe can handle multiple exceptions at a time in the method declaration
It can be used only with unchecked exception.It can be used for both checked and unchecked exceptions
It does not require try-catch to handle the exceptionIt is the responsibility of the called method to handle the exception using the try-catch

Reference

Translate »