Checked exceptions force users to explicitly handle them; they are used for “recoverable” exceptions, where the user can handle the situation gracefully.
Take FileNotFound - it is usually thrown when the file is missing, and below is the associated 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(); } }
Here, the checked exception forces me to declare it in a try / catch block, where I can close fis gracefully, even if there is an exception.
Now consider that FileNotFound is an exception at runtime, the code will hypothetically look like this:
FileInputStream fis = null; fis = new FileInputStream(new File("")); fis.close();
Now, if this throws a runtime exception that you don't need to handle at compile time, your fis will not be gracefully closed and this is a resource leak.
source share