In this section, we will learn what the `throws` keyword is and how it works in Java exception handling.
Java throws Exception
If a piece of code may throw a checked exception, we must do one of the following:
- Handle the checked exception by placing the piece of code inside a `try-catch` block.
- Specify in the method/constructor declaration that it throws the checked exception. This is done via the `throws` keyword.
In the last few sections, we explained how to use `try-catch` block. Now in this section we’re going to see how we can design a method or constructor to pass an exception to other methods instead of handling it.
What is Java `throws` keyword?
Sometimes we put instructions in a method or a constructor that we know might produce one or more exceptions if the caller is not careful with arguments that it sets for the method.
In such case, we have two options:
- Either we handle those potential exceptions directly in the body of the method via `try-catch` blocks.
- Only set these types of exceptions in the declaration of the method or constructor and let the caller method to decide how it wants to handle these exceptions.
In the second option, we’re basically forwarding the exception handling from one method to another, and this is done via the `throws` keyword.
The `throws` keyword is placed after the closing parentheses of the method’s parameters list. The throws
keyword is followed by a comma-separated list of exception types. Recall that an exception type is nothing but the name of a Java class, which is in the exception class hierarchy.
How to use `throws` keyword in Java? `throws` keyword syntax
Consider a method named `openFile`. Now, in order to pass the potential exceptions in the body of this exception to the caller method, we can use the `throws` keyword as:
public void openFile() throws ExceptionName{/*…*/}
The throws keyword comes after the parentheses and before the block of the method.
Also, on the right side of the `throws` keyword we put the name of the exceptions that might occur in the target method.
Note: if there are multiple potential exceptions, we can put them all on the right side of the `throws` keyword and separate them using comma `,` like:
public void openFile() throws ExceptionName1, ExceptionName2, ExceptionName3{/*…*/}
Example: using throws keyword to handle exceptions
public class Simple { public static void main(String[] args) { try{ openFile ("file-address"); }catch (IOException exception){ System.out.println(exception.getMessage()); } } public static void openFile (String address) throws IOException{ FileInputStream fileInputStream = new FileInputStream(address); char c = (char)fileInputStream.read(); } }
Output:
file-address (The system cannot find the file specified)
How does throws keyword work in Java?
In the body of the `openFile()` method we’ve created an object of type `FileInputStream` which is used to access and open a file.
If the address that we set for the argument of the constructor of this object is not accurate, we might get an exception of type `IOException` class.
So now in this method we have two choices:
- Handle the exception right in this method.
- Forward this exception to the caller method.
Here, by declaring the type of exception that this method might produce via the `throws` keyword, we basically passed the handling of the exception to the caller method.
In a situation like this, the caller method can either handle the potential exception of the target method via `try-catch` blocks or it can pass it as well.
Note: the passing exception from one method to another goes up until it reaches the runtime engine which in that case, the runtime will send a message to the output stream. This message shows the class name, the method name and the line number of the location where the error occurred.
In the example above, the caller method of the `openFile()` is the `main()` method and as you can see, we’ve decided to handle the `IOException` by creating a `try-catch` block in this method.
So we set the `try` block and inside it we called the `openFile()` method. Now, if an exception occurs in this method, the exception is passed to the `main` method and the `catch` block of this `try` block will handle the exception.
Passing multiple thrown exceptions
In order to pass multiple exceptions that might be thrown from a method, we can use the `throws` keyword and put any potential exception of that method on the right side of this keyword each separated by a comma `,`.
Example: throwing multiple exceptions
public class Simple { public static void main(String[] args) { try{ openFile ("file-address"); }catch (IOException exception){ System.out.println(exception.getMessage()); } } public static void openFile (String address) throws IOException, Exception{ FileInputStream fileInputStream = new FileInputStream(address); char c = (char)fileInputStream.read(); } }
Output:
file-address (The system cannot find the file specified)
Java throws keyword notes:
- We can also mix the two options in the same method when a piece of code throws more than one checked exception. You can handle some of them using a try-catch block and declare some using a throws clause in method’s declaration.
- The Java compiler forces you to handle a checked exception either by using a block or by try-catch using a clause in the method or constructor declaration. If a method throws an exception, it should be throws handled somewhere in the call stack. That is, if a method throws an exception, its caller can handle it, or its caller’s caller can handle, and so on. If an exception is not handled by any callers in the call stack, it is known as an uncaught exception (or an unhandled exception). An uncaught exception is finally handled by the Java runtime, which prints the exception stack trace on the standard error and exits the Java application.
- Recall that a catch block with an exception type can handle an exception of the same type, or any of its subclass type. For example, a catch block with Throwable exception type is capable of handling all types of exceptions in Java, because the Throwable class is the superclass of all exception classes. This concept is also applicable to the `throws` clause. If a method throws a checked exception of Exception1 type, you can mention Exception1 type in its `throws` clause or any of the superclasses of Exception1. The reasoning behind this rule is that if the caller of the method handles an exception that is the superclass of Exception1, the same handler can also handle Exception1.
Difference between throw and throws in Java
In short, the `throw` keyword is used to manually throw an exception in a program. But the `throws` keyword is used to pass an exception that is already thrown to the enclosing scope (or basically the caller method that invoked the current method).
Java throws exception reference book:
Beginning Java 9 Fundamentals, 2nd Edition
Written by: Kishori Sharan