Throw And Throws Keywords In Exception Handling

Throw And Throws Keywords In Exception Handling
Throw And Throws Keywords In Exception Handling

Introduction

Exceptions date back to the dawn of programming. Exceptions were used to change the flow of the program and avoid hardware failures back when programming was done via low-level programming languages.

Today, many modern languages, such as Java, Python, and Ruby, provide powerful exception handling mechanisms. This feature makes a programming language robust.

This article includes several examples demonstrating how to use the “throw” and “throws” keywords in the exception handling process. To get a clear grasp of this blog, read its complementary blog. Exception handling in Java using try-catch and finally. That illustrates the first three keywords in Java exception handling.

Using throw and throws

Any code, either general or from a package written by someone else, such as the packages included with the Java platform and the Java runtime environment, can throw an exception. The throw keyword is always used to throw the exception, regardless of what causes it.

Similarly, keyword throws are used to declare exceptions that may occur in the program. Methods that can throw exceptions must use throws to list the anticipated exceptions.

As you may have seen, the Java platform has a significant number of exception classes. All the classes are derived from Throwable, and they all allow programs to distinguish between the various forms of exceptions that can occur during program execution.

Let’s proceed to explore more about the throw and throws keyword.

The throw keyword

Good exception handling is essential for keeping our application running after the appearance of those undesirable moments.

To throw an exception explicitly from the code, we use the throw keyword.

A single argument is required for the throw statement: a throwable object. This object is an instance of any subclass of the Throwable class. 

For Example: Let’s take a closer look at the throw statement. The pop method in the following code comes from a class that implements an ordinary stack object. The method returns the object after removing the top element from the stack.

public Object pop() 
{
    Object obj;
if (size == 0) 
{ 
throw new EmptyStackException();
    	}

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}
  • The pop method examines the stack to see if any elements are present. Pop creates a new EmptyStackException object and throws it if the stack is empty.
  • The declaration of the pop method does not include a throws clause. Because EmptyStackException is a RuntimeException and its subclasses are unchecked exceptions. 
  • It is not mandatory to handle an unchecked exception or declare it in the throws clause inside a method or constructor.

Case 1: How to throw a built-in exception using the throw keyword

To throw an exception that is already defined in the Java library, we simply use the throw keyword. If the first number is zero, the program throws an ArithmeticException with the throw keyword in the example below.

import java.io.IOException;

public class TestThrow
{
	   static int sum(int num1, int num2)
	   {
	      if (num1 == 0)
	   {
          throw new ArithmeticException("First parameter is zero!!");
         }

	      else
	         System.out.println("Addition is possible!!");
	      
	      return num1+num2;
	   }
	   public static void main(String args[])
	   {
	      int ans = sum(0,12);
	      System.out.println(ans);
	   }
}

Output
Exception in thread "main" java.lang.ArithmeticException: First parameter is zero!!
	at TestThrow.sum(TestThrow.java:8)

Case 2: How to throw a custom exception using the throw keyword

To throw an exception that isn’t defined in the Java library, we must create a custom exception class to define the exception that we want to throw. 

In the example below, if the age is less than 18, the program throws an instance of the custom exception class using the throw keyword. Also, notice that we have used the throw and throws keyword simultaneously in this program.

class CustomException extends Exception
{  
 CustomException(String s){  
  super(s);  
 }  
} 

public class ChainedExceptionTest
{  
  static void validate(int age)throws CustomException
  {  
     if(age<18)
throw new CustomException("Invalid Age");  
     else  
      System.out.println("Successful!!");  
   }  
     
   public static void main(String args[])
   {  
      try{  
      validate(13);  
      }
catch(Exception ex)
      {
    	  ex.printStackTrace();
      } 
  }  
} 

Output
CustomException: Invalid Age
	at ChainedExceptionTest.validate(ChainedExceptionTest.java:12)

The throws keyword:

In Java programming, the throws keyword is used to declare an exception in the program. It notifies the programmer that an exception may occur. Hence the programmer should provide exception handling code to maintain the regular flow in the program execution.

Syntax:

<returntype> methodname() throws ExceptionClassName{...}

Example: Here’s a program that demonstrates how the throws keyword can propagate checked exceptions.

import java.io.IOException;
public class TestThrows 
{
	void method1()throws IOException
	{  
	    throw new IOException("System Error!!");//checked exception  
	}  
	void method2()throws IOException
	{  
	    method1();  
	}  
	  void method3()
	  {  
	   try
	   {  
		   method2();  
	   }
	   catch(Exception e)
	   {
		   	System.out.println("Exception handled in catch block!!");
	   }  
	  }  
	  public static void main(String args[])
	  {  
	   TestThrows obj=new TestThrows();  
	   obj.method3();  
	   System.out.println("The Normal flow continued!!");  
	  }  
}

Output
Exception handled in catch block!!
The normal flow continued!!

Case 1: Handling the exception using try-catch block

If you handle the exception using try-catch, the code will run smoothly irrespective of whether the exception occurs during the run or not.

Programme:

import java.io.*;  
class Test
{  
	void method()throws IOException
	{  
		throw new IOException("System error!!");  
	}  
}  
public class TestThrows
{  
   public static void main(String args[])throws IOException
   {
	   try 
	   {
		   Test m=new Test();  
		   m.method();  
	   }
	   catch(Exception e)
	   {
		   	System.out.println("Exception handled in catch block!!");
	   }
    	System.out.println("The Normal flow...");  
   }  
}

Output
Exception handled in catch block!!
The Normal flow...

Case 2: Declaring the exception using throws

If you declare an exception, the code will normally execute if the exception does not occur. An exception will be thrown at runtime if an exception occurs because throws do not handle exceptions.

Program when an exception occurs:


import java.io.*;  
class Test
{  
	void method()throws IOException
	{  
		throw new IOException("System error!!");  
	}  
}  
public class TestThrows
{  
   public static void main(String args[])throws IOException
   {
	   //declare exception  
	   Test m=new Test();  
	   m.method();  
  
    System.out.println("The Normal flow...");  
  }  
} 

Output
Exception in thread "main" java.io.IOException: System error!!
	at Test.method(TestThrows.java:6)
	at TestThrows.main(TestThrows.java:15)

Program when an exception does not occur:

import java.io.*;  
class Test
{  
	void method()throws IOException
	{  
		  System.out.println("Device operation performed!!");  
	}   
}  
public class TestThrows
{  
   public static void main(String args[])throws IOException
   {
	   //declare exception  
	   Test m=new Test();  
	   m.method();  
  
    System.out.println("The Normal flow...");  
  }  
} 

Output
Device operation performed!!
The Normal flow…

Difference between throw and throws

There are numerous differences between throw and throws keywords in exception handling.

Following are some of the primary differences between throw and throws keywords in Java:

Sno.throwthrows
1.Used to explicitly throw an exception in Java.Used to declare an exception in Java.
2.A checked exception cannot be propagated using the keyword throw.A checked exception can be propagated with throws.
3.An instance follows the throw keyword.A class follows the throws keyword.
4.The throw keyword is used inside a method.The throws keyword is used with the method signature.
5.Multiple exceptions cannot be thrown using the throw keyword.Multiple exceptions can be declared using the throws keyword.

Chained Exceptions

JDK 1.4 introduced an important concept in Java known as Chained Exceptions. This feature allows programmers to relate one exception with another in the program. In simpler terms, one exception may specify the reason for another. 

For example, when a method throws an ArithmeticException to divide an integer by zero, the actual cause is an I/O event providing zero value to the divisor. The method will only throw an ArithmeticException. But if we use the getCause() method present in a chained exception, it’ll show the actual cause of the exception. 

Chained exceptions help us know the exact reason that led to an exception, rather than just displaying the exception information.

Two new constructors and two new methods are added to the Throwable class to enable chained exceptions in java.

Constructors in Java that support chained exceptions:

  • Throwable(Throwable cause)
  • Throwable(String msg, Throwable cause)

Here, msg is the exception message, and the cause is the exception that caused the current exception.  

These two constructors have also been added to the Error, Exception, and RuntimeException classes.

Methods in Java that support chained exceptions:

  • The method getCause() returns the actual cause of the current exception. If there is no underlying exception, null is returned.
  • The method initCause(Throwable cause) sets the cause for the calling exception. The cause exception can be set only once. Thus, we can call this method only once for each exception object.

Note: If a constructor already sets the cause of the exception, we can’t set it again using initCause( ). In general, initCause( ) is used to set a cause for legacy exception classes that don’t have the two extra constructors mentioned before.

Program to demonstrate chained exception: 

In this case, the program throws an ArithmeticException using “throw”, but the real cause of the problem was an IOException. The initCause() method is used to set the cause of an exception.

import java.io.IOException;

public class ChainedExceptionTest
{
    public static void divide(int a, int b)
    {
      if(b == 0)
      {
        ArithmeticException ae = new ArithmeticException("The Top Layer of Exception!!");
        ae.initCause(new IOException("The cause of the exception initialised by initCause method!!"));
        throw ae;
      }
      else
      {
        System.out.println(a/b);
      }
    }

    public static void main(String[] args)
    {
      try 
      {
        divide(15, 0);
      }
      catch(ArithmeticException ae) {
        System.out.println( "Caught exception at Top Layer: " +ae);
        System.out.println("The Actual cause of the exception: "+ae.getCause());
      }
    }
}

Output:
Caught exception at Top Layer: java.lang.ArithmeticException: The Top Layer of Exception!!
The Actual cause of the exception: java.io.IOException: The cause of the exception initialised by initCause method!!

Purpose of Exception Handling

When an exception occurs, the main purpose of exception handling is to ensure that the program’s flow does not break and the program executes all the statements present.

For example, if an exception occurs in a program. The statements after the exception will not be executed, and the programme will end abruptly. By handling, we ensure that all statements are executed and that the program’s flow is not disrupted.

Exception handling is more about accepting those bizarre things that can happen during the execution of a program’s lifecycle. Depending on the type of “bizarre thing” that happens, we may be able to recover from it.

In Java, exception handling refers to the management of errors. It’s a technique of gracefully handling program errors. 

Three Recently Added Exception Features

The exception system has been enhanced with three new and valuable features in JDK 7. 

  • When a resource, such as a file, is no longer needed, the first feature automates the process of releasing it. It’s based on try-with-resources, which is an enhanced version of the try statement.
  • The second feature is called multi-catch. It allows a catch clause to catch two or more exceptions at the same time. Instead of needing to catch each exception type separately, we can handle all exceptions with a single catch clause, avoiding code duplication.
  • The third is sometimes referred to as final rethrow or, more precise rethrow. Only those checked exceptions associated with throws of the try block, which are not handled by a preceding catch clause, and a subtype or supertype of the parameter, can be rethrown with the more precise rethrow feature.

Want to learn more about how to take advantage of improved exception handling? Read the official documentation of  Working with Java SE 7 Exception Changes.

Frequently Asked Questions

Which type of exception should be declared?

Two main types of exceptions should be declared as given below:
Unchecked Exceptions: that are under the programmer’s control.
Error: that is beyond the programmer’s control.

Can we re-throw an exception in our program?

Yes, we can re-throw an exception by throwing the same exception in the catch block.

What is the purpose of the throw and throws keywords in Java?

Throwing an exception inside a method is done with the throw keyword. On the other hand, the throws keyword indicates that a method may throw one or more exceptions.

Which keyword is used to throw an exception in Java manually?

The keyword “throw’ is used for throwing exceptions manually in Java.

What happens after the throw exception?

After a method throws an exception, the runtime system attempts to find something to handle it. The exception handler chosen is said to catch the exception.

Key Takeaways

This article discusses the importance and usage of throw and throws keywords in Java, along with chained exceptions and the purpose of exception handling. 

Java exception handling uses five keywords to handle exceptions: try, catch, finally, throw, and throws.

To read how try-catch and finally keywords are utilized to handle errors and exceptions in java, we recommend you to visit the article Exception Handling in Java using try-catch and finally.

By Vaishnavi Pandey