throws keyword in Java with examples

throws keyword :

In Java, the throws keyword is used in method declarations to specify that the method may throw one or more checked exceptions. Checked exceptions are those exceptions that are subclasses of java.lang.Exception but not subclasses of java.lang.RuntimeException. They represent exceptional conditions that the method might encounter during its execution, and the Java compiler enforces the handling of these exceptions. 

throws keyword syntax:

return_type method_name(parameter_list) throws exception_type1, exception_type2, ... {
    // method implementation
}
throws keyword code example :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {

    // Method that reads the contents of a file and throws IOException
    public static void readFile(String filePath) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    public static void main(String[] args) {
        String filePath = "example.txt";
        try {
            readFile(filePath);
        } catch (IOException e) {
            System.err.println("An IOException occurred: " + e.getMessage());
        }
    }
}

Next Post Previous Post
No Comment
Add Comment
comment url