0% found this document useful (0 votes)
63 views4 pages

Difference Between Throw and Throws in Java

Uploaded by

Ishan Singhal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views4 pages

Difference Between Throw and Throws in Java

Uploaded by

Ishan Singhal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

throw and throws in Java

In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular
flow of the application can be preserved. It handles runtime errors such as NullPointerException,
ArrayIndexOutOfBoundsException, etc. To handle these errors effectively, Java provides two key
concepts, throw and throws.

Java throw

The throw keyword in Java is used to explicitly throw an exception from a method or any block of
code. We can throw either checked or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.

Syntax of throw in Java: throw Instance(Object)

Where instance is an object of type Throwable (or its subclasses, such as Exception).

Example: throw new ArithmeticException(“/ by zero”);

But this exception i.e., Instance must be of type Throwable or a subclass of Throwable.

The flow of execution of the program stops immediately after the throw statement is executed and
the nearest enclosing try block is checked to see if it has a catch statement that matches the type of
exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try
block is checked, and so on. If no matching catch is found then the default exception handler will
halt the program.

Example 1: This example demonstrates where an exception is thrown, caught, and re-thrown inside
a method.

// Java program to demonstrate

// how to throw an exception

class Geeks {

static void fun()

try {

throw new NullPointerException("demo");

catch (NullPointerException e) {

[Link]("Caught inside fun().");

throw e; // rethrowing the exception

public static void main(String args[])

try {

fun();

catch (NullPointerException e) {

[Link]("Caught in main.");

}
Output:

Caught inside fun().

Caught in main.

Java throws

throws is a keyword in Java that is used in the signature of a method to indicate that this method
might throw one of the listed type exceptions. The caller to these methods has to handle the
exception using a try-catch block.

Syntax of Java throws

type method_name(parameters) throws exception_list

where, exception_list is a comma separated list of all the exceptions which a method might throw.

In a program, if there is a chance of raising an exception then the compiler always warns us about it
and compulsorily we should handle that checked exception, Otherwise, we will get compile time
error saying unreported exception XXX must be caught or declared to be thrown. To prevent this
compile time error we can handle the exception in two ways:

1. By using try catch

2. By using the throws keyword

We can use the throws keyword to delegate the responsibility of exception handling to the caller (It
may be a method or JVM) then the caller method is responsible to handle that exception.

Example: Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":

public class Main {

static void checkAge(int age) throws ValidateException {

if (age < 18) {

throw new ValidateException("Access denied - You must be at least 18 years old.");

else {

[Link]("Access granted - You are old enough!");

}
public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

Important Points:

 throws keyword is required only for checked exceptions and usage of the throws keyword
for unchecked exceptions is meaningless.

 throws keyword is required only to convince the compiler and usage of the throws keyword
does not prevent abnormal termination of the program.

 With the help of the throws keyword, we can provide information to the caller of the
method about the exception.

Common questions

Powered by AI

When a method uses the 'throws' keyword, its signature is appended with 'throws' followed by a list of potential exceptions. This change signals to the caller that they must address these exceptions, typically through catching them in a try-catch block or propagating them further by also declaring them in the calling method's signature. It effectively informs the caller about expected exceptional scenarios, ensuring that appropriate error handling mechanisms are in place .

The 'throw' keyword is used to manually throw an exception, which can be either checked or unchecked. It allows programmers to explicitly trigger exceptions, providing more control over the flow of error handling . The 'throws' keyword, however, is primarily concerned with checked exceptions. It is used in a method declaration to signify that the method could throw specified exceptions, requiring the calling method to handle these exceptions either through a try-catch block or further delegation via 'throws'. This mechanism ensures that checked exceptions are either caught or declared, adhering to Java's compile-time checks .

The 'throws' keyword should be used in scenarios where a method is responsible for potentially throwing checked exceptions, but the programmer prefers to delegate the handling of these exceptions to the caller rather than handling them within the method itself. This can simplify a method if it performs basic error-prone operations where detailed exception handling isn't necessary, or when designing an API where the exception handling should be determined by the API user rather than the method .

Handling exceptions is crucial in Java to ensure that runtime errors do not cause the program to crash or become unresponsive. Proper exception handling allows a program to gracefully recover from unexpected events, maintain regular execution flow, and provide meaningful feedback to the user. Neglecting exception handling can lead to program crashes, resource leaks, loss of data, and a poor user experience due to uninformative error messages or breakdowns during execution .

The 'throws' keyword has no practical requirement concerning unchecked exceptions as these are not enforced to be caught or declared by the compiler. Unchecked exceptions, a subclass of RuntimeException, indicate programming errors or misuse of API that a program is free to handle or ignore. As a result, using 'throws' with them is purely informative and not functionally necessary .

When the 'throw' keyword is executed, the normal flow of execution is interrupted, and control is transferred to the nearest enclosing try-catch block that can handle the exception type being thrown. If a matching catch block is found, control is passed to that block. If none is found within the immediate context, the search continues up the call stack until a suitable catch block is found or, failing that, the default exception handler halts the program execution .

Failing to declare a checked exception with the 'throws' keyword in the method signature results in a compile-time error. Java's strict compile-time checks enforce that any checked exceptions must be either caught or declared, ensuring that the program addresses potential exceptional circumstances reliably. Not declaring these exceptions with 'throws' leaves the method non-compliant with these checks, leading to an 'unreported exception must be caught or declared to be thrown' error by the compiler .

The 'throw' keyword in Java is used within a method to explicitly throw an exception, either checked or unchecked, which typically represents an error or an unusual circumstance that occurred during the execution of the program . In contrast, the 'throws' keyword is used in the method's signature to declare that the method might throw one or more exceptions, thus transferring the responsibility for handling these exceptions to the calling method .

Re-throwing an exception can be useful when a method needs to handle part of the exception's context or log it without taking responsibility for fully handling the exception, effectively allowing the calling method to address it. For instance, a method might catch an exception for logging purposes or cleanup, then re-throw it to allow further handling or cleanup by a higher-level method or the method's caller, which might have more context about how to proceed from that point .

An educational example involves a method that performs age validation. The method 'checkAge' might declare 'throws ValidateException' indicating the caller must handle this exception. Within 'checkAge', if the age is below 18, a 'throw new ValidateException' is used to trigger an exception. This setup demonstrates both keywords: 'throws' communicates potential exceptions to the caller, while 'throw' is used to signal an error condition programmatically, showing how exception declaration and throwing work together to manage error handling .

You might also like