Explain about checked and unchecked Exceptions with Examples?
Checked Exceptions - These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptions extend the java.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses.
For example if you call the readLine() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throws java.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well-written application and will also prompt to correct the file name.
Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.
Lets take the same file name example as described earlier. In that example the file name is passed to the constructor for FileReader. However, the constructor will throw NullPointerException if a logic error causes a null to be passed to the constructor. Well in this case the exception could be caught by the application but it would rather try to eliminate the bug due to which the exception has occurred. You must have encountered the most common exception in your program i.e. the ArithmeticException. I am sure you must be familiar with the reason of its occurrence that is when something tries to divide by zero. Similarly when an instance data member or method of a reference variable is to be accessed that hasn't yet referenced an object throws NullPointerException.