Checked and Un checked Exceptions in Java
This “Checked and Un checked Exceptions in Java” page is providing clear information about difference between Checked and Un checked exceptions using example codes in java.
Un checked: (by compiler)
- Un checked exception occurs only in case of logical error.
- Java application not connected to outside resource(other program like images, files, database, servers…).
- Handling of Unchecked exception takes care by programmer only.
- Compiler does not report, though we don’t handle unchecked exception.
- Handling unchecked exception avoids abnormal termination of program.
Checked : (by compiler)
- While working with any outside resource (file, server, database, io devices…..), chance to get Checked Exception.
- After working with outside resource, it is mandatory to release (shutdown) the resource properly to avoid loss of data.
- Outside resource is not the property of Java application. Hence we must handle every checked exception in the application.
- If not, compiler reports error and class file will not be generated.
- While using Method or Constructor in the application, we need to consider the complete prototype.
- Following diagram describes an example with its prototype.
Example code that describes Handling Checked Exception(in Opening File):
Checked Exception Handling
public FileInputStream(String name) throws FileNotFoundException
opens a file in read mode....
import java.io.FileInputStream ;
public static void main(String args)
FileInputStream fis = new FileInputStream("g:/input.txt");
System.out.println("File opened successfully...");
catch (FileNotFoundException fnfe)
System.out.println("file doesn't exist....");