Kubernetes  

Difference between Throw and Throws in Exception Handling

Introduction

 Exception handling is an essential part of Java programming that ensures the smooth execution of applications even when unexpected errors occur. Two important keywords used in this context are throw and throws. Although they look similar, their roles are completely different. In this article, we will understand both keywords in detail, with examples and key differences. Whenever a program does not want to handle exceptions using the try block, it can use the throws clause. The throw statement is used to explicitly throw an exception.

Throw in Java

The throw keyword is used to explicitly throw an exception from a method or any block of code. It is typically used when you want to force an exception to occur based on a certain condition.

  •  throw is used inside a method or block.

  •  It is followed by an exception object.

  • Only one exception can be thrown at a time using throw.

Syntax

throw new ExceptionType("Error Message");

The example below illustrates throwing a new instance of an exception, then re-throwing the same exception to the outer handle. 

class ThrowDemo {
    static void demoproc() {
        try {
            throw new NullPointerException("demo");
        } catch (NullPointerException e) {
            System.out.println("Caught inside demoproc");
            throw e; 
        }
    }
    public static void main(String[] args) {
        try {
            demoproc();
        } catch (NullPointerException e) {
            System.out.println("Recaught: " + e);
        }
    }
}

This code demonstrates that the throw is used to re-throw an exception from the catch block. The exception is first caught inside demoproc() and then caught again in main().

Output

Throws in Java

The throws keyword is used in a method declaration to indicate that the method may throw one or more exceptions. It informs the caller of the method that it needs to handle these exceptions, either with try-catch or by further declaring throws.
The throws clause is responsible for handling the different types of exceptions generated by the program. This clause usually contains a list of the various types of exceptions that are likely to occur in the program.

  • throws is used in the method signature.

  • It is followed by exception class names (not objects).

  • Multiple exceptions can be declared with throws.

Let us discuss with the help of an example

class ThrowsException
{
public static void main(String args[])throws ArithmeticException
{
System.out.println("Inside Main");
int i=0;
int j=40/i;
System.out.println("This statement is not printed");
}
}

The main() of this program except for the generation of ArithmeticException, but it does not want to handle it using the try/catch block. Hence, the inclusion of the throws clause in the definition of this method. Note that, after the display of the description of the Exception, the program terminates abruptly. The last print statement in the program is never executed.

Output

Difference between throw and throws 

throwthrows
Used to explicitly throw an exceptionDeclares that a method may throw an exception
Inside a method or blockIn method signature
Exception object (e.g., new IOException())Exception class name(s) (e.g., IOException)
Can throw only one exception at a timeCan declare multiple exceptions
StatementPart of method declaration

For Example

import java.io.*;
public class CombinedExample {
    public void readFile() throws IOException {
        throw new IOException("File not found!");
    }
    public static void main(String[] args) {
        CombinedExample obj = new CombinedExample();
        try {
            obj.readFile();
        } catch (IOException e) {
            System.out.println("Exception handled: " + e.getMessage());
        }
    }
}

Use throw when you want to throw an exception inside a method. Use throws when you declare that a method may throw an exception. Both are integral to Java’s exception handling mechanism, but serve different purposes.

Output

Summary

 The keywords throw and throws in Java exception handling serve different purposes. throw is used inside a method or block to explicitly throw a single exception object, stopping further execution until handled. On the other hand, throws is used in a method declaration to indicate that the method may throw one or more exceptions, passing the responsibility to the caller to handle them. Both are essential for managing runtime errors and ensuring smooth program execution.