How to throw an exception in Java

In this tutorial, we will learn how to throw an exception in Java. We use exceptions in Java to check for errors at compile-time instead of runtime. We can also create custom exceptions to make the code easy to read and debug.

Throwing an exception in Java

Throw keyword

To throw an exception explicitly, we use the keyword throw. We can use it to throw checked,  unchecked or custom exceptions.

Syntax:

throw new ExceptionClassName("Message");

Throwing checked exception

To throw a checked exception, we use the throw keyword along with the catch block or declare the method using throws keyword. Here is a sample code showing both of these cases.

Example

import java.io.FileNotFoundException;
import java.io.FileReader;

public class excpt {
  //Declaring the method using throws keyword as it might throw an exception
  public static void getFile() throws FileNotFoundException {
    FileReader file = new FileReader("nonExistingFile.txt");
    //throws an exception
    throw new FileNotFoundException();
  }
  //main method with try and catch to show exception handling 
  public static void main(String args[]) {
    try {
      getFile();
    }
    catch(FileNotFoundException e){
      e.printStackTrace();
    }
    //rest of the code
  }
}

Output

java.io.FileNotFoundException: nonExistingFile.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at exception.excpt.getFile(excpt.java:9)
at exception.excpt.main(excpt.java:16)

Throwing unchecked exception

To demonstrate unchecked exception we have a check method that accepts an integer as its parameter. This method checks if a number is less than 10 and if the number is less than 10, we throw an ArithmeticException.

Example

public class exceptDemo {
  public static void check(int num) {
    //throwing an arithmetic exception if the number is less than 10
    if(num<10) {
      throw new ArithmeticException("Number is less than 10");
    }
    else {
      System.out.println("valid number.");
    }
  }
  public static void main(String args[]) {
    check(8);
    //rest of the code
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Number is less than 10
at exception.exceptDemo.check(exceptDemo.java:7)
at exception.exceptDemo.main(exceptDemo.java:14)

This is how we can throw an exception in Java. Here is something you can read next Exception Handling Comparison in C++ and Java.

Leave a Reply

Your email address will not be published. Required fields are marked *