throws keyword in Java

In this article, we will discuss throws keyword or throws clause in detail with example

try-catch block:

Whenever a program might raise exception, then it must be handled. In all earlier articles, we handled exception using try-catch block. For example,

But try-catch block isn’t only option to handle exception; let us remove try-catch block from one of the examples that we already discussed and see what exactly compiler has to say

From above screen capture, it is clear that whenever a program might raise/throw exception, then are there are 2 options to handle that exception

  1. surrounding with try-catch block (Surrounding with try/catch)
  2. using throws clause (Add throws declaration)

Note: compiler force the programmer to handle only checked exception

 

throws keyword or throws clause:

  • throws keyword is used to declare exception that might raise during program execution
  • whenever exception might thrown from program, then programmer doesn’t necessarily need to handle that exception using try-catch block instead simply declare that exception using throws clause next to method signature
  • But this forces/tells caller-method to handle that exception; but again caller can handle that exception using try-catch block or re-declare those exception with throws clause/keyword
  • In other words it can also be stated that, it provides information to caller-method, that possible exception might raise during program execution and it need to be handled
  • Note: use of throws clause doesn’t necessarily mean that program will terminate normally rather it is the information to the caller to handle for normal termination
  • Any number of exceptions can be specified using throws clause, but they are all need to be separated by comma (,)
  • throws clause is applicable to methods & constructor but strictly not applicable to classes
  • Compiler forces programmer to handle only checked exception; so it can be handled either-way using throws clause or try-catch block
  • For unchecked exception, it is programmer choice; as unchecked exception by default propagated back to the caller method when it isn’t handled
  • In addition to checked & unchecked exception, user-defined exception or custom exception can also be specified using throws clause
  • But user-defined exception or custom exception must be of type Throwable class or one of its sub-class (i.e.; extend either Throwable class or any one of its sub-class like Exception, IOException, RuntimeException, Error, etc)
  • Otherwise, compile-time error will be thrown stating “incompatible type

Syntax of throws clause:

public static void printFileContent() throws FileNotFoundException;

 

We will cover various cases for throws clause, like

  1. Handling checked exception using try-catch block by caller-method
  2. Re-declaring checked exception using throws clause by caller-method
  3. Default exception propagation for unchecked exception
  4. Any number of exceptions can be declared using throws clause
  5. Constructor can also declare exception using throws clause

 

Case 1: Caller method handling checked exception using try-catch block, when it encounters throws clause in the target method

CallerHandlingExceptionUsingTryCatchBlock.java

package in.bench.resources.exception.handling;

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

public class CallerHandlingExceptionUsingTryCatchBlock {

	public static void main(String[] args) {

		// invoking method
		try {
			printFileContent();
		} 
		catch (FileNotFoundException fnfex) {
			System.out.println("Exception handled ... \n" +
					fnfex.getMessage());
		}
	}

	// throws clause for checked exception
	public static void printFileContent() 
			throws FileNotFoundException {

		// assumed that, 
		// we are trying to access file from remote location
		FileReader fileReader = new FileReader(
				"D:/Folder/test.txt");

		// reading & processing file
	}
}

Output:

Exception handled ... 
D:\Folder\test.txt (The system cannot find the path specified)

 

Case 2: Caller method re-declare checked exceptions using throws clause, when it encounters throws clause in the target method

CallerHandlingExceptionUsingThrowsClause.java

package in.bench.resources.exception.handling;

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

public class CallerHandlingExceptionUsingThrowsClause {

	public static void main(String[] args) throws FileNotFoundException {

		// invoking method
		printFileContent();

		System.out.println("Successful : reading & processing completed !!");
	}

	// throws clause for checked exception
	public static void printFileContent() throws FileNotFoundException {

		// assumed that, we are trying to access file from remote location
		FileReader fileReader = new FileReader("test.txt");

		// reading & processing file
	}
}

Output:

Successful : reading & processing completed !!

Explanation:

  • If the specified path isn’t available at runtime during program execution then invoking method with “throws FileNotFoundException” result in raising exception which is propagated to caller-method i.e.; main() method
  • main() method also doesn’t handle exception rather it is re-declared, and
  • therefore program terminates abnormally
  • finally prints stack trace in the console

 

Case 3: Default exception propagation for unchecked exception

ThrowsKeywordWithUncheckedException.java

package in.bench.resources.exception.handling;

public class ThrowsKeywordWithUncheckedException {

	public static void main(String[] args) {

		// invoking method
		anotherMethod(null);
	}

	public static void anotherMethod(String str) {

		if(str == null){
			throw new NullPointerException(
					"Please send some valid String");
		}

		// further processing with the string value
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException: 
			Please send some valid String
			at in.bench.resources.exception.handling
			.ThrowsKeywordWithUncheckedException.anotherMethod(
					ThrowsKeywordWithUncheckedException.java:19)
			at in.bench.resources.exception.handling
			.ThrowsKeywordWithUncheckedException.main(
					ThrowsKeywordWithUncheckedException.java:9)

Explanation:

  • When unchecked exception is thrown/raised then compiler never complains with compile-time error
  • Reason: it is due to the lack of proper coding and pre-condition checking by programmer
  • Therefore, it is duty of programmer to do proper coding to handle all possible types of unchecked exception in the program
  • Otherwise, program terminate abruptly when last entry of the runtime stack is reached and
  • default exception handler takes care of printing exception information in the console

 

Case 4: Any number of exceptions can be declared using throws clause, with each exception-type is separated by comma (,)

NumberOfExceptionsDeclaredUsingThrowsClause.java

package in.bench.resources.exception.handling;

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

public class NumberOfExceptionsDeclaredUsingThrowsClause {

	public static void main(String[] args) {

		// invoking method
		try {
			printFileContent();
		} 
		catch (FileNotFoundException fnfex) {
			System.out.println("Exception handled ... \n"
					+ fnfex.getMessage());
		}
	}

	// throws clause for checked exception
	public static void printFileContent() 
			throws FileNotFoundException, ArithmeticException,
			NullPointerException {

		// assumed that, 
		// we are trying to access file from remote location
		FileReader fileReader = new FileReader(
				"D:/Folder/test.txt");

		// reading & processing file

		// arithmetic calculation 
		int result = 19/0;

		// string computation 
		String str = null;
		System.out.println("The length of the String is : "
				+ str.length());
	}
}

Explanation:

  • From above example, it is clear that using throws clause, any number of exception can be declared with comma separating them
  • There are 3 types of exceptions are declared (both including checked & unchecked exception)
  • Whenever checked-exception is raised/thrown, then compiler forces/tells programmer to handle exception either with try-catch block or throws clause
  • For unchecked-exception like ArithmeticException or NullPointerException, it is propagated back up in the runtime stack by-default and compiler never complain with any compile-time error
  • That’s reason, caller-method has to handle only FileNotFoundException
  • Whereas it is a choice to programmer either to handle unchecked-exception for graceful termination or else it will be handled by Default exception handler when no handler-code is available
  • Giving control to Default exception handler result in abnormal termination

 

Case 5: Constructor can also declare exception using throws clause

  • It is valid to declare exception for Constructor using throws clause
  • This is required whenever Constructor does some job which might raise exception while constructing Object
  • In the below example, Constructor tries to read file from some drive location which might raise FileNotFoundException (or it’s super-type IOException) when Object is constructed

ConstructorDeclaringExceptionUsingThrowsClause.java

package in.bench.resources.exception.handling;

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

public class ConstructorDeclaringExceptionUsingThrowsClause {

	// default constructor
	public ConstructorDeclaringExceptionUsingThrowsClause(String str) 
			throws FileNotFoundException {

		// assumed that, 
		// we are trying to access file from remote location
		FileReader fileReader = new FileReader(str);

		// reading & processing file
		System.out.println("Successful: File reading & processing done !!");
	}

	public static void main(String[] args) 
			throws FileNotFoundException {

		ConstructorDeclaringExceptionUsingThrowsClause cdeutc = 
			   new ConstructorDeclaringExceptionUsingThrowsClause(
						"test.txt");
	}
}

Output:

Successful: File reading & processing done !!

 

Try-catch block v/s throws clause for checked exception:

  • Whenever we try to handle some checked-exception using try-catch block and that checked-exception might never raise then compile-time error will be thrown stating “Unreachable catch block for IOException. This exception is never thrown from the try statement body
  • This is applicable only when handling checked-exception using try-catch block; but compiler never throws compile-time error for declared checked exception using throws clause

Error-scenario : Screen-capture for try-catch block when checked exception never arises

No error for throws clause:

  • Screen-capture for throws clause when checked exception never arise
  • But when same checked exception is declared using throws clause, then it never complains & also never raises any compile-time error like in earlier case

In the following articles, we will see

 

References:

 

Read Also:

 

Happy Coding !!
Happy Learning !!

throw v/s throws in Java
throw keyword in Java