Difference Between throw and throws in Java

The words “throw” and “throws” in Java are used by programmers to describe potential problems that might appear unexpectedly while a program is running. The method for overcoming these problems is exception handling. They are used in many different situations and computer languages, and they have a variety of functions.

“throw”:

The keyword “throw” is frequently used in programming languages to explicitly raise or cause an exception. If an extraordinary event or error occurs while a program is being executed, you can use “throw” to expressly generate an exception, signalling that something unexpected has happened. This approach is typically taken when a programmer runs into a problem that requires stopping the program’s normal flow. The program’s control flow is then transferred to the closest applicable exception-handling code after “throw” has been used.

“throws”:

In function and method declarations, the word “throws” denotes the possibility that the code will throw one or more different exception types when called. It serves as a means of informing callers of the function or method that they must propagate or handle such exceptions. The developer indicates that the caller must take into account the possibility of exceptions being thrown by that function or method by stating “throws” in the function signature.

Prerequisite:

“Throw” and “throws” are integral aspects of exception handling in Java. The “throw” keyword facilitates the deliberate throwing of exceptions within a specific method or code block. On the other hand, the “throws” keyword finds its place in method signatures. It indicates that a method might potentially give rise to certain exceptions during its execution. In essence, “throw” is employed to explicitly generate exceptions, while “throws” is included in method declarations to highlight the possibility of exceptions being generated.

Difference between throw and throws Keyword in Java:

Aspect throw throws
  

 Usage

Used inside a method to manually throw an exception. Used in method declarations to specify potential exceptions that might be thrown by the method.
 

 Syntax

throw exceptionInstance; returnType methodName(parameters) throws ExceptionType1, ExceptionType2, …;
 What It Does Signals an exceptional condition within the method. Declares the exceptions that the method might propagate to its caller.
 Handling Requires the caller to catch or propagate the thrown exception. Informs the caller about the exceptions that need to be handled when calling the method.
 Exception Type Followed by an instance of an exception class or a subclass of Throwable. Followed by a comma-separated list of exception classes.
 Checked/Unchecked Can be used to throw both checked and unchecked exceptions. Declares both checked and unchecked exceptions that might be thrown.
 In Method Body Used inside a method’s body to explicitly throw an exception. Not used within the method body; only in the method’s declaration.
 Mandatory Not mandatory; used when the programmer wants to throw an exception. Not mandatory; used to indicate the potential exceptions the method might throw.

Example Program:

import java.io.IOException;

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("An arithmetic exception occurred: " + e.getMessage());
        }
    }

    public static int divide(int numerator, int denominator) throws ArithmeticException {
        if (denominator == 0) {
            throw new ArithmeticException("Division by zero!");
        }
        return numerator / denominator;
    }
}

Output:

An arithmetic exception occurred: Division by zero!

Explanation:

Import Statement: import java.io.IOException; is the first import statement in the code. The IOException import is not being used in this code sample, thus it may be removed without having any negative effects on how the program behaves.

ExceptionExample is a class that has been declared. The main method, which is the program’s entry point, is contained in this class.

Main Method: The main method is where the execution of the program begins. The division function is called inside the try block with the inputs 10 and 0. An error will be raised because this function call tries to divide 10 by 0.

A try-catch block is used in the programming to manage exceptions. Due to the attempt to divide by zero, when the divide function is called, it throws an ArithmeticException. The catch block that follows catches this exception.

Catch Block: Using e.getMessage(), the catch block publishes an error message after catching the ArithmeticException. This error message denotes a division by zero miscalculation.

Method: divide The divide method is a public static int divide(int numerator, int denominator) that raises an ArithmeticException. Numerator and denominator, two integer parameters, are required for this procedure. This method may throw an ArithmeticException, as indicated by the throws ArithmeticException phrase in the method signature.

Division Check: The condition if (denominator == 0) is used within the divide method to check for division by zero. A new ArithmeticException is thrown with the message “Division by zero!” if the denominator is 0.

Throw Statement: When a division by zero circumstance arises, the throw statement generates and throws an exception. The normal program flow is interrupted, and control is then passed to the closest suitable catch block.

Returning Result: The divide method computes the outcome by dividing the numerator by the denominator and then returns the outcome if the division is legitimate (the denominator is not zero).

Program 1:

Using “throw” to Custom Exception:

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class ThrowCustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (CustomException e) {
            System.out.println("Custom Exception caught: " + e.getMessage());
        }
    }

    public static void validateAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("You must be at least 18 years old.");
        }
        System.out.println("Age is valid.");
    }
}

Output:

Custom Exception caught: You must be at least 18 years old.

Explanation:

The CustomException exception type is created by this software by extending the Exception class. The validateAge function throws this specific exception if the user is under the legal drinking age of 18. Due to the age being under 18, the main method calls validateAge(15), which raises the particular exception. Both the exception’s capture and the error message are written in the main method’s try-catch block.

Program 2:

Using “throws” in Method Signature:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            readFromFile("example.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO Exception: " + e.getMessage());
        }
    }

    public static void readFromFile(String filename) throws FileNotFoundException, IOException {
        FileReader reader = new FileReader(filename);
        int character;
        while ((character = reader.read()) != -1) {
            System.out.print((char) character);
        }
        reader.close();
    }
}

Output:

File not found: example.txt (The file “example.txt” does not exist in this context)

Explanation:

This application’s readFromFile function uses the filename parameter to attempt to read characters from a file. Because throwing exceptions is allowed in both the constructor for the FileReader and the read method, the throws clause in the method signature also includes the exceptions FileNotFoundException and IOException.

The readFromFile function is called by the main method with the argument “example.txt,” even though there isn’t a file with that name in this case. A FileNotFoundException is raised as a result, and the catch block prints the relevant error message.

Throws keyword Vs. try…catch…finally:

  • The “throws” keyword is used at the method declaration level to indicate which exceptions might be propagated to the caller.
  • The “try…catch…finally” construct is used within a specific code block to handle exceptions that might occur during the execution of that block.

Summary:

While “throws” is used to indicate that a function or method may throw a certain exception in its declaration, “throw” is used to manually raise exceptions. For effective programming exception handling, both are necessary.