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
- try-catch block example
- finally block example
- nested try-catch block example
- returning value from method containing try-catch—finally blocks
- return statement from finally 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,
- What types of exception can be thrown using throw keyword ?
- What is the impact on caller method, when checked or unchecked exception is raised ?
- What happens to the statements, after throw keyword or throw clause ?
- What happens, if the throwing exception object is actually referring to null reference ?
- 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 keyword, then 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:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!