dsa

Java throw and throws

In this tutorial, we will learn to use throw and throws keyword for exception handling with the help of examples.

In Java, exceptions can be categorized into two types:
1.Unchecked Exceptions: They are not checked at compile-time but at run-time.For example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, exceptions under Error class, etc.
2.Checked Exceptions: They are checked at compile-time. For example, IOException, InterruptedException, etc.
This tutorial will now focus on how to handle checked exceptions using throw and throws.

Java throw keyword

throw – We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

Syntax of Java throw

throw throwableObject;

A throwable object is an instance of class Throwable or subclass of the Throwable class.

Example: Java throw Keyword

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Trying to divide by 0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
    at Main.divideByZero(Main.java:3)
    at Main.main(Main.java:7)
exit status 1  

In this example, we are explicitly throwing an ArithmeticException.

Java throws keyword

throws – When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

Syntax of Java throws

accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
  // code
}

As you can see from the above syntax, we can use throws to declare multiple exceptions.

Example: Java throws Keyword

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    // code that may produce IOException
    File newFile=new File("test.txt");
    FileInputStream stream=new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try{
      findFile();
    } catch(IOException e){
      System.out.println(e);
    }
  }
}

Output

java.io.FileNotFoundException: test.txt (No such file or directory)

When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.

throws keyword Vs. try...catch...finally

There might be several methods that can cause exceptions. Writing try...catch for each method will be tedious and code becomes long and less-readable. throws is also useful when you have checked exception (an exception that must be handled) that you don't want to catch in your current method.

Advantage of exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.