No announcement
 

Types of exception

There are two types of exception in Java namely, Checked Exception and Unchecked Exception.

Checked Exception

Checked exceptions are checked by the compiler during compile time to check whether the exception has been handled in the code (also known as compile time exception). If not, then a compilation error is thrown. E.g., IOException, SQLException.

Example:

CheckedExceptionDemo.java

package com.codingnous.tutorial;

import java.io.FileInputStream;

public class CheckedExceptionDemo {

	public static void main(String[] args) {

		// Checked exception.
		FileInputStream fi = new FileInputStream("D:\\SampleInput.txt");

	}
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at com.codingnous.tutorial.CheckedExceptionDemo.main(CheckedExceptionDemo.java:10)

Unchecked Exception

Unchecked exception occur during the execution of the program (also known as runtime exception). These exceptions are not checked by the compiler as it is beyond the implementation of compiler itself. Like logical error or incorrect usage of API.

Example:

UncheckedExceptionDemo.java

package com.codingnous.tutorial;

public class UncheckedExceptionDemo {

	public static void main(String[] args) {

		int i = 10, j = 0;

		System.out.println("i/j= " + (i / j));

	}
}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.codingnous.tutorial.UncheckedExceptionDemo.main(UncheckedExceptionDemo.java:9)