Difference between Checked and Unchecked Exception
Checked Exception:
Checked exceptions are a concept in Java (and some other programming languages) used to handle exceptional conditions that may arise during the execution of a program. Unlike unchecked exceptions (runtime exceptions), checked exceptions must be explicitly handled by the programmer, either by using a try-catch block or by declaring them in the method signature using the throws keyword.Some Checked Exceptions in Java are : IOException, FileNotFoundException, SQLException, ParseException, ClassNotFoundException, etc.
There are two types of keywords for Checked Exception :
1) throws
2) try-catch block
throws : In Java, the throws keyword is used in method declarations to indicate that the method may throw a specific exception during its execution. When a method declares that it throws an exception using the throws keyword, it is essentially stating that it will not handle the exception within the method and will instead propagate it to the calling method or the JVM.
throws keyword syntax:
returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {
// method body
}
throws keyword code example:import java.io.*;
public class FileReadExample {
// Method that declares it may throw an IOException
public static void readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("example.txt"));
// Code to read from the file...
br.close();
}
// Method that calls readFile() and handles the IOException
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
// Handle the IOException here
e.printStackTrace();
}
}
}
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} finally {
// Optional: Code that always executes, whether there's an exception or not
}
try catch keyword code example:public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This method may throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Exception occurred: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
public static int divide(int dividend, int divisor) {
return dividend / divisor; // This line may throw ArithmeticException if divisor is 0
}
}
Unchecked Exception:public class UncheckedExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // This line will throw an ArithmeticException (division by zero)
System.out.println("Result: " + result);
}
}
Difference between Checked and Unchecked Exception: