Checked Exceptions force users to explicitly handle them, they are used for 'recoverable' exceptions, where the user can handle the situation gracefully.
Let's take a FileNotFound
- it is typically thrown when the file is not present and below is a related programming idiom:
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(""));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The Checked Exception here forces me to declare it in a try/catch block, where I can close the fis
gracefully even if there's an exception.
Now consider that FileNotFound
is a runtime exception, the code hypothetically will look like below:
FileInputStream fis = null;
fis = new FileInputStream(new File(""));
fis.close();
Now if this throws a runtime exception - which you do not need to handle at compile time, your fis
will not be closed gracefully and that is a resource leak.