In this Java tutorial, you will learn how to use the throw and throws keyword in Java with code examples.
The throw keyword is used to throw an exception from within a method. When a throw statement is encountered and executed, execution of the current method is stopped and returned to the caller.
Whereas the throws keyword is used to declare that a method may throw one or some exceptions. The caller has to catch the exceptions (catching is optional if the exceptions are of type unchecked exceptions).
These two keywords are usually used together as depicted the following form:
void aMethod() throws Exception1, Exception2 { // statements... if (an exception occurs) { throw new Exception1(); } // statements... if (another exception occurs) { throw new Exception2(); } }
An interface declares a method that throws an exception:
interface AutoMobile { void startEngine() throws EngineStartException; void go(); }
Where EngineStartException is a subclass of Exception class whose super type is Throwable:
class EngineStartException extends Exception { }
A typical usage of throw statement and throws clause together:
void deleteFile(File file) throws FileNotFoundException { if (!file.exists()) { throw new FileNotFoundException(); } file.delete(); }
The following example shows a method must declare to throw an exception because it contains the code that may throw an exception:
void writeToFile(String filePath) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); // writes to file... }
The method parseInt() in the following code may throw a NumberFormatException which is an unchecked exception, so the method is not required to catch or throw that exception:
int parseNumber(String input) { int number; // this may throw unchecked exception: NumberFormatException number = Integer.parseInt(input); return number; }
See all keywords in Java.