Friday 29 August 2014

Checked versus unchecked exceptions

I get asked this question in interviews. "What is the difference between checked and unchecked exceptions? "
It's a questions that any programmer with a bit of experience should know.
It's not a difficult question but I do tend to miss out some points occasionally, so I though I'd write down the differences here:

Unchecked exceptions:

  • These are actual bugs in the program, so bugs which reflect errors in the logic of your program. Programs with unchecked exceptions will compile just fine, but when they run, they will break. For example, if you wrote a program to divide by 0, it would compile, but when you run it you will see a ArithmeticException. The most common unchecked exception you will see as a Java developer is most likely to be the NullPointerException.

Checked exceptions:
  • These are foreseen bugs in the program, they will stop the program compiling. An example of a checked exception would be the FileNotFoundException. pretty self explanatory really, but if you write a program which reads in a file using something like FileInputStream, it will error with a unhandled exception type FileNotFoundException, so you must use try catch, or throw the exception.


No comments:

Post a Comment