Blog |

How to use the Throws keyword in Java (and when to use Throw)

How to use the Throws keyword in Java (and when to use Throw)
Table of Contents

Imagine you're a postal worker sorting through a mountain of packages. Some packages are ticking suspiciously, while others are leaking mysterious liquids. As a responsible postal worker, you have two choices: deal with these problematic packages yourself (throw) or slap a big "HANDLE WITH CARE" sticker on them and pass them along to the next person in line (throws).

Think of throw as actually creating an error in your program. You use it when something goes wrong and you want to stop the program. For example, you might use throw if someone enters an invalid password.

On the other hand, throws is like a warning sign. You write it after the name of a function to say, "Hey, this part might cause an error." It doesn't actually create the error; it just warns that an error could happen. You usually see throws next to functions that might have problems, like reading a file that might not exist.

In short, throw makes errors happen, while throws just warns about possible errors.

Java Throws Keyword

The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown. The throws keyword provides information about the exceptions to the programmer as well as to the caller of the method that throws the exceptions.

The throws keyword allows exceptions to be propagated in the call stack. When a method declares that it throws an exception, it is not required to handle the exception. The caller of a method that throws exceptions is required to handle the exceptions (or throw them to its caller and so on) so that the flow of the program can be maintained.

Only checked exceptions are required to be thrown using the throws keyword. Unchecked exceptions don’t need to be thrown or handled explicitly in code.

Java Throws Example

Here is an example of a method that throws an exception, which is handled by the caller of the method:

public static void writeToFile() throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter("myFile.txt"));
    bw.write("Test");
    bw.close();
}

public static void main(String[] args) {
try {
        writeToFile();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

In the above example, the “writeToFile” method throws an IOException and declares it using the throws keyword to its callers. The “main” method calls the “writeToFile” method and handles the exception within a try-catch block, and prints the exception stack trace to the console.

Java Throws Syntax

The throws syntax in Java is shown below:

type method (arguments) throws Exception1, Exception2, … {  }

As seen in the syntax above, all exceptions that can be thrown by a method should be declared in the method signature using the throws keyword. A method can throw multiple exceptions, which should be separated by a comma in the declaration.

Java Throw Keyword

The throw keyword in Java is used for explicitly throwing a single exception. This can be from within a method or any block of code. Both checked and unchecked exceptions can be thrown using the throw keyword.

When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.

The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application.

Unchecked exceptions can be propagated in the call stack using the throw keyword in a method. Checked exceptions can be propagated using the throw keyword when the method that throws the exception declares it using the throws keyword.

Java Throw Syntax

The throw syntax in Java is shown below:

throw throwableObject;

A throwable object can be an instance or subclass of the Throwable class. All exceptions defined in Java are subclasses of Throwable.

Java Throw Example

private static List <Integer> integers = new ArrayList <Integer>();

public static void addInteger(Integer value) throws IllegalArgumentException {
    if (integers.contains(value)) {
        throw new IllegalArgumentException("Integer already added.");
    }
    integers.add(value);
}

public static void main(String[] args) {
    try {
        addInteger(1);
    } catch (IllegalArgumentException iae) {
        iae.printStackTrace();
    }
}

In this example, the “addInteger” method throws an IllegalArgumentException using the throw keyword in case the “integers” ArrayList object already contains the integer passed.

Since IllegalArgumentException is a checked exception, it must be handled within the “addInteger” method or its caller. In this example, the “addInteger” method does not handle the exception and throws it to the caller using the throws keyword.

Therefore the caller, “main”, has to handle the IllegalArgumentException using a try-catch block.

Java Throw vs Throws

The table below lists the difference between the throw and throws keywords in Java:

Throw Throws
Used within a method (or constructor) Used with method (or constructor) signature
Used to throw an exception explicitly Used to declare exceptions
Can only throw a single exception Can declare multiple exceptions
Followed by a throwable instance Followed by an exception class name
Cannot be used to propagate checked exceptions by itself Can be used to propagate checked exceptions by itself

Track, Analyze and Manage Errors With Rollbar

Throw java exceptions with Rollbar
Throw java exceptions with Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Rollbar can help throw Java exceptions as well as track, analyze, and manage errors in real-time to help you to proceed with more confidence. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape