Master java skills

Throws Keyword

Throws keyword is used along with method declaration. It tells the callers of that method that this method may throw one or more certain exceptions. All those exceptions are declared as part of method declaration.

Syntax of throws clause

public int calculate (int num1, int num2) throws ArithmeticException, NullPointerException {
    //code line1
    //code line2
}

When some exceptions might occur inside a method, but we don’t want to handle them using try-catch-finally blocks, we have to include them as part of throws clause. Below are some important points about throws clause:

  1. throws clause is used along with method declaration.
  2. If not handled inside the method, all possible checked exceptions must be included in the throws clause. If checked exceptions are neither handled nor included as part of throws clause, there will be compiler error.
  3. Unchecked exceptions may or may not be included as part of throws clause. If not included, there won’t be a compilation error.
  4. If interface method has throws clause, its implementation method must have throws clause with all the checked exceptions that interface method has.

throws example

In the below example, we haven’t used try-catch block. Instead, we have included possible exceptions in the throws clause of the method calculate(). But remember even if we didn’t use throws clause here, there wouldn’t have been any problem. Now, it’s time for you to think why. We have mentioned the same in the point number 3 above.

package com.javatrainingschool;

public class ThrowsClauseExample {
	
	public static int calculate(int num1, int num2) throws ArithmeticException, ArrayIndexOutOfBoundsException {
		
		int result = num1/num2;
		int [] arr = new int[] {1,2,3,4};
		
		int arrVal = arr[result];
		return arrVal;
	}
	
	public static void main(String[] args) {
		
        int val = calculate(12, 3);
        System.out.println("Value is = " + val);
		
	}		
}
Output :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at com.sks.ExceptionExample.calculate(ExceptionExample.java:10)
	at com.sks.ExceptionExample.main(ExceptionExample.java:16)

Checked exceptions in throws clause example

In the below example, throws clause has checked exceptions. It means it is mandatory to include them in the throws clause given that we are not going to handle them using try-catch block.

Please note that the method readFile() which has throws clause is called inside main method. Now, there are two ways: either handle the thrown exceptions by readFile() method in the main() method using try-catch block. Or, add throws clause in main() method as well for the same exceptions which are included in the throws clause of readFile() method.

Caller method handle throws clause exceptions using try-catch block as shown below:

package com.javatrainingschool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ThrowsClauseExample {

	public static void readFile() throws FileNotFoundException, IOException {
		
		File file = new File("C:\\Users\\saras\\Desktop\\test.txt");
		BufferedReader bf = new BufferedReader(new FileReader(file));
		String str = null;
		while((str = bf.readLine()) != null) {
				System.out.println(str);
		}
	}
        public static void main (String [] args) {
		try {
			readFile();
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFoundException caught in main method");
		} catch (IOException e) {
			System.out.println("IOException caught in main method");
		}
	}
}

Caller method also include exceptions in its throws clause as shown below:

package com.javatrainingschool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ThrowsClauseExample {

	public static void main (String [] args) throws FileNotFoundException, IOException {
		readFile();
	}
	
	public static void readFile() throws FileNotFoundException, IOException {
		
		File file = new File("C:\\Users\\saras\\Desktop\\test.txt");
		BufferedReader bf = new BufferedReader(new FileReader(file));
		String str = null;
		while((str = bf.readLine()) != null) {
				System.out.println(str);
		}
	}
}

Difference between throw and throws

throw and throws, both keyword are used for different purposes. Let’s see what are some differences between the two.

throwthrows
‘throw’ keyword is used to throw an exception programmatically.‘throws’ keyword is used to declare the exceptions which may be thrown from a method.
Using throw keyword we have to throw an instance of an exception type.throws keyword is followed by the class names of the exception type.
Using throw, we can throw only one exception at a timeUsing throws we can declare multiple exceptions
Checked and unchecked, both kinds of exceptions can be thrown.Checked and unchecked, both kinds of exceptions can be declared in throws clause.
Even a custom exception can be thrown using throw keywordCustom exceptions can also be included in the throws clause