Generally, checked exceptions occurs when application code dealing with external resources like file, database, network connection, servers etc. So checked exceptions don’t raise because of programming mistake, They raise because of external resources unavailability. So we can’t avoid checked exceptions. But we have to handle them and define an alternative way when checked exceptions raised. Let us discuss the with the following example.
Example 01 : checked exception – checked by compiler – compilation error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.vidvaan.corejava.exception15.handleChecked; import java.io.FileInputStream; // checked exception - checked by compiler - compilation error public class Example01CheckedException { // Here we are not handling exceptions public static void main(String[] args) { System.out.println("main begin"); FileInputStream fis = null; // constructor FileInputStream(File filename) throws FileNotFoundException, // FileNotFoundException is a checked exception fis = new FileInputStream("demo.txt"); int c; // Method FileInputStream.read() throws a checked exception:IOException while ((c = fis.read()) != -1) { System.out.print((char) c); } // Method FileInputStream.close() throws a checked exception:IOException fis.close(); System.out.println("main end"); } } |
Compilation Errors :
Example01CheckedException.java:15: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
fis = new FileInputStream(“demo.txt”);
^
Example01CheckedException.java:19: error: unreported exception IOException; must be caught or declared to be thrown
while ((c = fis.read()) != -1) {
^
Example01CheckedException.java:24: error: unreported exception IOException; must be caught or declared to be thrown
fis.close();
^
3 errors
In the above example, We are reading the file demo.txt
and displaying its content on the console. We got three compilation errors as we mentioned in the comments of the program. We can fix the above compilation errors in two ways as shown below.
Example 02 : checked exception – declare exception with throws keyword
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.vidvaan.corejava.exception15.handleChecked; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; // checked exception - declare exception with throws keyword public class Example02CheckedExceptionDeclare { // Here we are declaring IOException, FileNotFoundException with throws keyword public static void main(String[] args) throws IOException, FileNotFoundException { FileInputStream fis = null; // constructor FileInputStream(File filename) throws FileNotFoundException, // FileNotFoundException is a checked exception fis = new FileInputStream("demo.txt"); int c; // Method FileInputStream.read() throws a checked exception:IOException while ((c = fis.read()) != -1) { System.out.print((char) c); } // Method FileInputStream.close() throws a checked exception:IOException fis.close(); System.out.println("main end"); } } |
In the above example, We are declared both IOException and FileNotFoundException on main() method signature to avoid compilation errors. We can also declare like public static void main(String args[]) throws IOException
. Because IOException is super class for FileNotFoundException. But it always advisable to declare all possible exceptions instead super class of all the possible exceptions.
Declaring exceptions on main() method is not advisable because it is final place where we should handle exceptions. If this program fails to read file content, it leads to abnormal termination of the program. So the remaining code which is not related file reading also won’t execute.
We can declare exceptions on methods(not main() method) where ever you feel that, the caller method would take decision what need to be done when exception is raised.
For example Consider constructor FileInputStream(File filename) throws FileNotFoundException. Here they are not handling exception in constructor, Just they are declaring exception. If we have a requirement that, if ‘demo.txt’ not exist then we need to read ‘sample.txt’. If FileInputStream constructor handled exception with try catch block, Then how would caller knows whether the file loading is success or not? So declaring exception is required in some cases.
Example 03 : checked exception – handle exception with try-catch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.vidvaan.corejava.exception15.handleChecked; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; // checked exception - handle exception with try-catch public class Example03CheckedExceptionHandle { public static void main(String[] args) { System.out.println("main begin"); FileInputStream fis = null; // Here we are handling exceptions with try-catch block try { // constructor FileInputStream(File filename) throws FileNotFoundException, // FileNotFoundException is a checked exception fis = new FileInputStream("demo.txt"); int c; // Method FileInputStream.read() throws a checked exception:IOException while ((c = fis.read()) != -1) { System.out.print((char) c); } } catch (FileNotFoundException e) { System.out.println("Not found demo.txt :" + e.getMessage()); } catch (IOException e) { System.out.println("I/O error occurred while reading file :" + e.getMessage()); } finally { // Method FileInputStream.close() throws a checked exception:IOException try { fis.close(); } catch (IOException e) { System.out.println("I/O error occurred while closing stream :" + e.getMessage()); } } System.out.println("main end"); } } |
In the above example, We are handling the exception with try-catch block. It runs fine and display the content if file exist and reading passed. If file doesn’t exist or reading failed, then the above program clearly show the reason for failure and avoids abnormal termination of the program so that if there is any remaining code that will execute smoothly.