The throw keyword
Any code can throw exceptions, including your code, a code from the standard library or a code from a package written by someone else. Regardless of what throws the exception, it's always thrown with the keyword throw.
- throwing an instance of Throwable
throw new Throwable("An error occurs");
- throwing an instance of Exception
throw new Exception("An exception occurs");
- throwing an instance of RuntimeException
throw new RuntimeException("An exception occurs");
- throwing an instance of NullPointerException
throw new NullPointerException("NPE");
But it's impossible to throw an instance of another class:
throw new Long(10L); // this code is not compiled
So, the general form of the throw statement include the keyword throws and an object to be thrown.
Throwing checked exceptions from methods
Remember, there are two types of exceptions: checked and unchecked exceptions. Any method (static or instance) can throw them.
- If a method throws a checked exception outside, the exception must be written in the method declaration after the keyword throws. Otherwise, the will not be compiled.
For example, the following method reads text from a file, if the file is not found, the method throws an instance of IOException:
public static String readTextFromFile(String path) throws IOException {
// find a file by the specified path
if (!found) {
throw new IOException("The file " + path + " is not found");
}
// read and return text from the file
}
Here is only a part of the method. But the keyword throws followed the method parameters is required because IOException is checked.
- If a method throws two or more checked exceptions, they must be written in the method declaration like:
public static void method() throws ExceptionType1, ExceptionType2, ExceptionType3
- If a method throws two or more checked exceptions that extend another exception (BaseExceptionType), you may write only the base exception in the method declaration:
public static void method() throws BaseExceptionType
Throwing unchecked exceptions from methods
- If a method throws an unchecked exception, the keyword throws is optional (but not throw!). Usually, the exception is not written in the method declaration.
The method deposit of the class Account adds the specified amount to the current balance. If the amount is not positive or greater than the edge, the method throws IllegalArgumentException.
class Account {
private long balance = 0;
public void deposit(long amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Incorrect sum " + amount);
}
if (amount >= 100000000000L) {
throw new IllegalArgumentException("Too large amount");
}
balance += amount;
}
public long getBalance() {
return balance;
}
}
As you can see, the method declaration does not need throws IllegalArgumentException. The same thing with other unchecked exceptions including RuntimeException, NullPointerException, IndexOutOfBoundsException and so on.