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();
    }
}

 

Some Rules about throw and throws keywords in Java:

    •           Exception1, Exception2, …: the exception class must be a direct subclass of Throwableclass one of its subclasses.
    •           The throws keyword can be followed by one more exception class, separated by commas.
    •           The throw keyword must be followed by an instance of Throwable class or one of its subclasses.
    •           When using the throw keyword to throw a checked exception from within a method, the method must either:
        •      Declares the throws clause followed by the exceptions thrown by the throw statements, or:
        •     Catches the exceptions thrown by the throw statements.
    •           When a method contains statements which may throw exceptions (not using throw statements explicitly), it also has to either catch or declare to throw the exceptions.
    •           If the throw statements throw unchecked exceptions, the method is not required to declare those unchecked exceptions in its throws clause.
    •           A concrete method can declare throws clause if only if its body throws checked exceptions. Otherwise a compile error occurs.
    •           An interface’s method can declare throws clause freely.
    •           The throws clause can declare exceptions which are super types of the exception thrown by the throw statements, but not sub types.

 

Java throw and throws Code Examples

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.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#5SHIZhongping2018-09-11 22:30
As for the rule:
A concrete method can declare throws clause if only if its body throws checked exceptions. Otherwise a compile error occurs.

But the following code can compile without any error via oracle JDK 8u162:

import java.io.IOException;

public class TryCatchTest {
public void test() throws IOException {}
}
Quote
#4sravanthi2017-10-31 07:57
Hey if you throw a checked exception, It should be handled by catch keyword else there would be a compiletime error
Quote
#3AMIT2017-09-12 02:47
I want to know that a throw keyword can throw checked and unchecked exception or it can only throw unchecked exception coz whenever i am trying to make a program where it has to throw checked exception , it shows me compile time error like :- Unhandled Exception type FileNotFoundException.
Quote
#2vidya2017-02-28 01:02
can i write
class demo extends Exception throws IOEXception,NullPointerException
Quote
#1John2015-11-19 04:12
Thanks for sharing!
Quote