You will have seen earlier in all the programs of exception handling that Java runtime system (JVM) was responsible for identifying exception class, creating its object, and throwing that object.
JVM automatically throws system-generated exceptions. All those exceptions are called implicit exceptions. If we want to throw an exception manually or explicitly, for this, Java provides a keyword throw.
Throw in Java is a keyword that is used to throw a built-in exception or a custom exception explicitly or manually. Using throw keyword, we can throw either checked or unchecked exceptions in Java programming.
When an exception occurs in the try block, throw keyword transfers the control of execution to the caller by throwing an object of exception.
Only one object of exception type can be thrown by using throw keyword at a time. Throw keyword can be used inside a method or static block provided that exception handling is present.
Key points of Throw keyword:
1. In Java exception handling, we use throw keyword to throw a single exception explicitly. It is followed by an instance variable.
2. Using throw keyword, we can throw either checked or unchecked exception in Java.
3. The keyword throw raises an exception by creating a subclass object of Exception explicitly.
4. We mainly use throw keyword to throw custom exception on the basis of some specified condition.
5. We use keyword throw inside the body of method or constructor to invoke an exception.
6. With the help of throw keyword, we cannot throw more than one exception at a time.
Syntax of Throw Keyword
The syntax to throw an exception manually in Java is as follows:
throw exception_name;
Here, exception_name is a reference to an object of Throwable class or its subclass.
For example:
1. throw new ArithmeticException(); Or, ArithmeticException ae = new ArithmeticException(); throw ae; 2. throw new NumberFormatException();
Key points:
1. The object of Throwable class or its subclasses can be created using new keyword or using a parameter inside catch clause.
2. Instances of classes other than Throwable class or its subclasses cannot be used as exception objects.
Control flow of try-catch block with Java throw Statement
When a throw statement is encountered in a program, the flow of execution of subsequent statements stops immediately in the try block and the corresponding catch block is searched.
The nearest try block is inspected to see if it has a catch block that matches the type of exception. If corresponding catch block is found, it is executed otherwise the control is transferred to the next statement.
In case, no matching catch block is found, JVM transfers the control of execution to the default exception handler that stops the normal flow of program and displays error message on the output screen.
Java Throw Exception Example Program
In this section, we will know how to throw exception in Java manually. Let’s take an example program to throw an exception using new keyword.
Program code 1:
public class ThrowTest1 { public static void main(String[] args) { // Declaring a try-catch block. try { // Creating an object of ArithmeticException class. ArithmeticException a = new ArithmeticException("Hello from throw"); // Line 7 throw a; // Exception thrown explicitly. // Line 8 // Line 7 and 8 can be written also in one line like this: // throw new ArithmeticException("Hello from throw"); } catch(ArithmeticException ae) { System.out.println("ArithmeticException caught: \n" +ae); System.out.println(ae.getMessage()); } } }
Output: ArithmeticException caught: java.lang.ArithmeticException: Hello from throw Hello from throw
In the main() method of class ThrowTest1, the try block creates an object of ArithmeticException class with reference variable a and passing an argument of String type to its constructor. The exception object is then thrown by the statement: throw a;
The thrown exception object is caught by corresponding catch block and stored in ae. The ae.getMessage() displays a string message append along with the internally generated message.
Program code 2:
public class ThrowTest2 { public static void main(String[] args) { int x = 20; int y = 0; try { int z = x/y; // Exception occurred. // Line 9 System.out.println("Result: " +z); // Line 10 throw new ArithmeticException(); } catch(ArithmeticException ae) { System.out.println("Exception caught: \n" +ae); } } }
Output: Exception caught: java.lang.ArithmeticException: / by zero
As you can see in line 9, when an exception occurred, the rest of code (line 10) did not execute and the program control immediately transferred to catch block to handle the exception.
Program code 3:
public class ThrowTest3 { public static void main(String[] args) { int x = 20; int y = 0; try { int z = x/y; throw new ArithmeticException(); System.out.println("Result: " +z); // Unreachable code. } catch(ArithmeticException ae) { System.out.println("Exception caught: \n" +ae); } } }
Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code
In the preceding program, when we have written a statement after throw statement, we got unreachable code. Due to which code could not be compiled.
Program code 4:
public class ThrowTest4 { public static void main(String[] args) { int num = 1; for(num = 1; num <= 10; num++) { try { if(num == 5) throw new ArithmeticException("ArithmeticException"); else if(num < 2) throw new RuntimeException("RuntimeException"); else if(num > 9) throw new NullPointerException("NullPointerException"); } catch(Exception e) { System.out.println("Caught an exception"); System.out.println(e.getMessage()); } } } }
Output: Caught an exception RuntimeException Caught an exception ArithmeticException Caught an exception NullPointerException
Program code 5:
class Test1 extends Exception { } class Test2 extends Exception { } class Test3 extends Exception { } public class ThrowTest5 { public static void main(String[] args) { int num = 1; for(num = 1; num <= 10; num++) { try { if(num == 5) throw new Test1(); else if(num < 2) throw new Test2(); else if(num > 9) throw new Test3(); } catch(Exception e) { System.out.println("Caught an exception"); } } }}
Output: Caught an exception Caught an exception Caught an exception
Rethrowing an Exception in Java
Java version 7 introduces a mechanism rethrowing an exception. When an exception occurs in a try block, it is caught by a catch block inside the same method.
The same exception object out from the catch block can be rethrown explicitly using throw keyword. This is called rethrowing of exception in Java.
When the same exception object is rethrown, it preserves details of original exception. The following snippet code shows how to rethrow the same exception object out from catch block:
try { // Code that might throw Exception. } catch(Exception e) { // Rethrow the same exception. throw e; }
Let’s take an example program where we will throw StringIndexOutofBoundsException. This exception generally occurs when a string index out of range.
Program code 6:
public class A { void m1() { try { // Taking a string with 9 chars. Their index will be from 0 to 8. String str = "Scientech"; char ch = str.charAt(10); // Exception is thrown because there is no index with value 10. } catch(StringIndexOutOfBoundsException se) { System.out.println("String index out of range"); throw se; // Rethrow the same exception. } } } public class B { public static void main(String[] args) { // Create an object to class A and call m1() method. A a = new A(); try { a.m1(); } // Rethrown exception is caught by below catch block. catch(StringIndexOutOfBoundsException se) { System.out.println("Rethrow exception is caught here: " +se); } } }
In this program, there are two classes A and B. StringIndexOutOfBoundsException is thrown in m1() method of class A that is caught and handled by catch block in that method.
Now, we want to propagate exception details to another class B. For this, catch block of class A is rethrowing it into the main method of class B where it can be handled.
Hence, we can rethrow an exception from catch block to another class where it can be handled.
Let’s take another example program where we will catch an exception of one type and rethrow an exception of another type.
Program code 7:
public class A { public static void main(String[] args) { try { m1(); } catch(ArithmeticException ae) { System.out.println("An exception of another type is recaught: \n" +ae); } } static void m1() { try { int a[] = {1, 2, 3, 4, 5}; System.out.println(a[5]); // Exception is thrown because there is no index with value 5. } catch(ArrayIndexOutOfBoundsException aie) { System.out.println("Array index out of range: \n" +aie); throw new ArithmeticException(); // Rethrow another type exception. } } }
Output: Array index out of range: java.lang.ArrayIndexOutOfBoundsException: 5 An exception of another type is recaught: java.lang.ArithmeticException
In this example program, catch block catches ArrayIndexOutOfBoundsException, and rethrow another type ArithmeticException.
Throw keyword in Java programming language is mainly used to throw an exception manually. It takes the exception object of Throwable class as an argument. It can also be used to break a switch statement without using a break keyword.
In this tutorial, you have learned about throw keyword in Java with the help of simple examples. Hope that you will have understood the basic points of throw keyword and practiced all example programs.
Thanks for reading!!!