0
0
Javaprogramming~5 mins

Throws keyword in Java

Choose your learning style9 modes available
Introduction

The throws keyword tells the program that a method might cause an error that needs handling.

When a method might cause an error that it does not handle itself.
When you want to inform others using your method that they should prepare for possible errors.
When working with input/output operations that can fail, like reading files.
When calling methods that throw checked exceptions and you want to pass the responsibility up.
When you want to keep your method code clean by not catching exceptions inside it.
Syntax
Java
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
    // method body
}
You list the exceptions after the method signature using the throws keyword.
Multiple exceptions are separated by commas.
Examples
This method says it might throw an IOException, so callers must handle it.
Java
public void readFile() throws IOException {
    // code that might throw IOException
}
This method declares it might throw an ArithmeticException if division by zero happens.
Java
public int divide(int a, int b) throws ArithmeticException {
    return a / b;
}
This method can throw two types of exceptions, so both are listed after throws.
Java
public void process() throws IOException, SQLException {
    // code that might throw IOException or SQLException
}
Sample Program

This program defines a method readFile that declares it throws IOException. The main method calls it inside a try-catch block to handle possible errors.

Java
import java.io.*;

public class ThrowsExample {
    public static void readFile(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        System.out.println("First line: " + reader.readLine());
        reader.close();
    }

    public static void main(String[] args) {
        try {
            readFile("test.txt");
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}
OutputSuccess
Important Notes

The throws keyword only declares exceptions; it does not handle them.

Checked exceptions must be declared or caught; unchecked exceptions (like NullPointerException) do not need to be declared.

Use throws to pass responsibility for handling exceptions to the method caller.

Summary

The throws keyword tells others your method might cause an error.

It helps keep code clean by letting callers handle errors.

Always declare checked exceptions your method can throw.