Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Throw Keyword in Java | Java Throw Exception

You will have seen earlier in all the programs of Exception handling that Java runtime system 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 Keyword in Java


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.

The syntax to throw an exception manually is as follows:
Syntax:

throw exception_name;

where exception_name is a reference to an object of Throwable class or its subclass.

For example:

throw new ArithmeticException();
or
ArithmeticException ae = new ArithmeticException();
throw ae;

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 throw Statement in Java


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 source code 1:

public class ThrowTest1 
{
public static void main(String[] args) 
{
try
{
  ArithmeticException a = new ArithmeticException("Hello from throw");
  throw a; // Exception thrown explicitly.

// 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

Explanation:

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 source code 2:

public class ThrowTest2 
{
public static void main(String[] args) 
{
 int x = 20;
 int y = 0;
 try
 {
   int z = x/y; // Exception occurred.
   System.out.println("Result: " +z);
   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 the exception occurred, the rest of code (line 10) did not execute.

Program source 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 source code 4:

public class ThrowTest4 
{
public static void main(String[] args) 
{
 int num = 1;
 for(num = 1; 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 source 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  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 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 source 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 program where we will catch an exception of one type and rethrow an exception of another type.

Program source 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.

Final words
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.

The post Throw Keyword in Java | Java Throw Exception appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Throw Keyword in Java | Java Throw Exception

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×