Java Keyword: throws

class Example {
    String readUtf8(Path file) throws"This method may throw IOException" IOException {

        byte[] bytes = Files.readAllBytes(file);
        return new String(bytes, StandardCharsets.UTF_8);

The throws keyword (not to be confused with the throw keyword) is used in method declarations to indicate that the given exception type may be thrown by the method. If you call the readUtf8 method in the example above, the throws declarations tells you that you should be prepared to catch exceptions of type IOException.

Multiple exception types can be specified as follows:

int m() throws IOException, InterruptedException, TimeOutException {
    // ...

Checked exceptions that are thrown in the method must be declared in the throws clause unless they are caught within the method. Unchecked exceptions do not have this requirement and should therefore not be mentioned in throws declaration (although the language does not prohibit it). See Difference between Checked and Unchecked Exceptions.


Be the first to comment!