![]() |
VOOZH | about |
Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.
ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.
I/O Exception: This Program throws an I/O exception because of due FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the file system, Java forces us to handle error situations where the file is not present in the given location.
Implementation: Consider GFG.txt file does not exist.
Example 1-A:
Output:
Now let us do discuss how to handle FileNotFoundException. The answer is quite simple as we can handle it with the help of a try-catch block
Example 1-B:
File does not exist
Now let us discuss one more checked exception which is ClassNotFoundException. This Exception occurs when methods like Class.forName() and LoadClass Method etc. are unable to find the given class name as a parameter.
Example 2-A
Output:
Again now let us handle ClassNotFoundException using the try-Catch block.
Example 2-B
Class does not exist check the name of the class
SQLException - The SQLException is a checked exception that we need to handle explicitly.
In this example, we are trying to connect the PostgreSQL database from the Java program, here everything is syntactically correct but we haven't said to the compiler that the main method will be going to throw a SQLException. Because of this, it will give us a compile time error as shown in the below output image.
Example 3-A
Output:
We can handle this in two ways.
Example 3-B: throws
Output:
Example 3-C: try/catch
Output: