Java – throw keyword or clause

In this article, we will discuss throw keyword in detail with example

So far, we have seen numerous example in earlier articles where exception raised/thrown from try-block is get caught in the catch-block by supplying corresponding exception-type in the catch-block

1. Implicitly-thrown exception:

  • In above example we discussed, exceptions raised/thrown from try-block is often created by method from where exception is raised
  • After exception raised, control is given to JVM along with this exception object created by method
  • Which does further job like to check whether possible handling code available or NOT
  • Or else exception needs to be propagated up in the stack for handling code

2. Explicitly-thrown exception:

  • But sometimes, user or programmer can also throw/raise exception explicitly at runtime on the basis of some business condition
  • To raise such exception explicitly during program execution, we need to use throw keyword
  • Syntax: throw instanceOfThrowableType
  • Generally, throw keyword is used to throw user-defined exception or custom exception
  • Although, it is perfectly valid to throw pre-defined exception or already definition exception in Java like IOException, NullPointerException, ArithmeticException, InterruptedException, ArrayIndexOutOfBoundsException, etc.
  • We will study in detail about user-defined exception or custom exception in next article
  • Note: rest of the steps remain same as that of implicitly-thrown exception like checking whether handler-code is available or NOT
  • If not, going up in the runtime stack to check possible handler-code
  • Pseudo code:
try { 
          // some valid Java statements throw new RuntimeException(); 
} 
catch(Throwable th) { 
           // handle exception here 
          // or re-throw caught exception 
}

2.1 Example on throw keyword:

  • This program raises/throws NullPointerException explicitly using throw keyword

ThrowKeywordDemo.java

package in.bench.resources.exception.handling;

public class ThrowKeywordDemo {

	public static void main(String[] args) {

		// local variable
		String str = null;

		if(str == null) {

			// throw null pointer exception
			throw new NullPointerException();
		}

		// print count of 1st string
		System.out.println("Count = " + args[0].length());
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at in.bench.resources.exception.handling
	.ThrowKeywordDemo.main(ThrowKeywordDemo.java:13)

3. Now, this leads to couple of question on throw keyword like,

  1. What types of exception can be thrown using throw keyword ?
  2. What is the impact on caller method, when checked or unchecked exception is raised ?
  3. What happens to the statements, after throw keyword or throw clause ?
  4. What happens, if the throwing exception object is actually referring to null reference ?
  5. Whether it is valid to re-throw caught exception in catch-block ?

We will cover each question with examples, taking each one as one case

3.1 All types of exception can be thrown using throw keyword

  • Both checked-exception and unchecked-exception can be thrown using throw keyword
  • Error can also be thrown using throw keyword
  • In addition to already defined exception & error in Java, programmer can create user-defined exception and it can also be thrown using throw keyword
  • 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, RuntimeException, Error, etc)
  • Otherwise, compile-time error will be thrown stating “incompatible type

3.1.1 Example for checked exception:

  • This program has a method called calculate to do division
  • and it checks whether 2nd number is Zero
  • and accordingly raises/throws exception using throw keyword

ThrowKeywordForUncheckedException.java

package in.bench.resources.exception.handling;

public class ThrowKeywordForUncheckedException {

	public static void main(String[] args) {

		int result = calculate(19, 0);
		System.out.println("Result of Division : "
				+ result);
	}

	public static int calculate(int number1, int number2) {

		if(number2 == 0) {
			throw new ArithmeticException("divide by ZeeRoo");
		}
		return number1/number2;
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException:
	divide by ZeeRoo
	at in.bench.resources.exception.handling
	.ThrowKeywordForUncheckedException
	.calculate(ThrowKeywordForUncheckedException.java:14)
	at in.bench.resources.exception.handling
	.ThrowKeywordForUncheckedException.
	main(ThrowKeywordForUncheckedException.java:7)

3.1.2 Example for error:

  • This is the sample program to showcase, it is valid & possible to throw error as well using throw keyword
  • Simply, while invoking a method called errorCondition throw error with user-defined message

ThrowKeywordForError.java

package in.bench.resources.exception.handling;

public class ThrowKeywordForError {

	public static void main(String[] args) {

		// invoking
		errorCondition();
	}

	public static void errorCondition() {

		// this is just demo purpose only
		throw new Error("Some Error message for User");
	}
}

Output:

Exception in thread "main" java.lang.Error:
	some error message for user
	at in.bench.resources.exception.handling.ThrowKeywordForError
	.errorCondition(ThrowKeywordForError.java:14)
	at in.bench.resources.exception.handling.ThrowKeywordForError
	.main(ThrowKeywordForError.java:8)

3.2 Impact on caller method, while invoking another method with throw keyword

3.2.1 Pre-defined exception

When a caller-method invokes another method which explicitly throws pre-defined or already defined exception using throw keyword, then

  • For checked exception, caller-method must be surrounded with try-catch block or re-throw caught exception
  • For unchecked exception & Error, caller-method doesn’t need to surround with try-catch block or re-throw caught exception
  • This is similar to the above example seen in case 1
  • Example – ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, etc.

3.2.2 User-defined exception or Custom exception

Similarly, when caller-method invokes another method which explicitly throws user-defined or custom exception using throw keyword, then

  • For user-defined exception which extends either pre-defined checked exception or one of it’s sub-class, then caller-method must be surrounded with try-catch block or re-throw caught exception
  • For user-defined exception which extends either pre-defined unchecked exception or one of it’s sub-class, then caller-method doesn’t need to surround with try-catch block or re-throw caught exception

ThrowKeywordForCheckedException.java

  • Below program invokes printFileContent method from main() method, which must be invoked within try-catch block
  • Because target-method might raise checked-exception during execution
package in.bench.resources.exception.handling;

import java.io.FileReader;
import java.io.IOException;

public class ThrowKeywordForCheckedException {

	public static void main(String[] args) {

		// must be surrounded with try-catch block compulsorily,
		// bcoz we are invoking method throwing checked exception
		try {
			printFileContent();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	// throwing checked exception
	public static void printFileContent() throws IOException {

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

		// throw IOException explicitly
		throw new IOException();
	}
}

Output:

java.io.IOException
	at in.bench.resources.exception.handling
	.ThrowKeywordForCheckedException.printFileContent(
			ThrowKeywordForCheckedException.java:21)
	at in.bench.resources.exception.handling
	.ThrowKeywordForCheckedException.main(
			ThrowKeywordForCheckedException.java:11)

Explanation:

  • In above example, main() method invokes another called printFileContent();
  • Which is trying to read file contents from local folder location
  • So, possibly checked-exception (i.e.; IOException for file accessing) can be thrown
  • Checked-exception are necessarily need to handle using try-catch block or throws keyword
  • For target method (i.e.; printFileContent), we are throwing IOException exception using throw keyword
  • And for the caller-method, which again need to handle this thrown exception when propagated from invoking method
  • So, here it is handled by surrounding within try-catch block
  • But important point to note here is that, when this is invoked from main() method then it is mandatory to invoke either within try-catch block or else declare throws clause for main method also
  • Note: we have used another keyword called throws keyword while throwing exception explicitly from invoking method; we will study in detail about throws keyword in the next article

3.3 Statements after throw keyword

  • Any statement after throw keyword is not reachable
  • If we try to write any statements after throw clause or throw keywordthen compile-time error will be thrown stating “Unreachable code” as shown in the below screen-capture

3.4 Thrown exception using throw keyword refers to null reference

  • In all earlier cases, we have explicitly thrown exception after creating exception using new keyword & thrown using throw keyword in single statement (or in one line)
  • But we can do the same in 2 steps like,
  • Step 1: create exception using new keyword in 1st line (1st statement)
  • Step 2: then throw created exception in 1st line using throw keyword in the second line (2nd statement)
  • But if the exception isn’t initialized in the step 1, then by-default it refers to null
  • So, while throwing uninitialized exception will result in NullPointerException during program execution

3.4.1 Valid case for properly initialized exception object:

  • Exception initialized in step 1
  • and in the next step, it is thrown/raised using throw keyword

3.4.2 Null Pointer Exception is thrown instead of Arithmetic Exception and program terminates abnormally

  • Here, second number is zero
  • so after checking condition in if statement, we are trying to throw Arithmetic Exception explicitly
  • But, Arithmetic Exception isn’t initialized and it refers to null
  • Therefore, instead of throwing Arithmetic Exception explicitly as coded by programmer
  • JVM catches null reference for explicitly throwing exception and throws Null pointer exception

ThrowKeywordUsingNullReference.java

package in.bench.resources.exception.handling;

public class ThrowKeywordUsingNullReference {

	public static void main(String[] args) {

		int result = calculate(19, 0);
		System.out.println("Result of Division : "
				+ result);
	}

	public static int calculate(int number1, int number2) {

		if(number2 == 0) {

			// creating Object of exception type
			ArithmeticException aex = null;

			// explicitly throwing ArithmeticException
			// using throw keyword
			throw aex;
		}
		return number1/number2;
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException
	at in.bench.resources.exception.handling
	.ThrowKeywordUsingNullReference.calculate(
			ThrowKeywordUsingNullReference.java:19)
	at in.bench.resources.exception.handling
	.ThrowKeywordUsingNullReference.main(
			ThrowKeywordUsingNullReference.java:7)

3.5 Re-throwing exception using throw keyword from caught exception in catch-block

It is possible & valid to re-throw caught exception in the catch-block. It is generally used in the below cases,

  • When a method catches exception and doesn’t want to handle, instead it want to propagate caught exception to caller-method (basically delegating responsibly to caller-method like manager-to-peer)
  • Sometimes, it can be used convert one exception-type into another exception and finally throw that exception-type
  • It is also used to add some user-message to caught exception before re-throwing to caller-method
  • Note: in all cases, it is the responsibility of caller-method to handle this exception either by surrounding with try-catch or declaring throws clause

ReThrowingCaughtException.java

package in.bench.resources.exception.handling;

public class ReThrowingCaughtException {

	public static void main(String[] args) {
		try {
			int result = divide(19, 0);
			System.out.println("Result of Division : "
					+ result);
		}
		catch(ArithmeticException aex) {
			System.out.println("The Divisor is ZeeRo,"
					+ " please enter some no-Zero number");
		}
	}

	public static int divide(int number1, int number2) {

		int result = 0;
		try {
			result = number1/number2;
		}
		catch(ArithmeticException aex) {
			throw aex;
		}
		return result;
	}
}

Output:

The Divisor is ZeeRo, please enter some no-Zero number

In the next article, we will discuss about throws keyword in detail with example

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - throws keyword or clause
Java - final v/s finally v/s finalize