Java Checked and unchecked exceptions

18-Sep-2024

Learn the difference between checked and unchecked exceptions and how to handle them in Java



Checked Exceptions are called complie-time exceptions. checked exceptions will check at compile time by the compiler. For examples , IOException, SQLException, etc.


Example of IOException


try {

FileReader file = new FileReader("myfile.txt"); // FileNotFoundException

} catch (FileNotFoundException exception) {

System.out.println("FileNotFoundException caught: " + exception.getMessage());

}




UnChecked Exceptions are called run-time exceptions. unchecked exceptions will check at run time. For examples , NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, etc.


Example of NullPointerException:



try {

String str = null;
System.out.println(str.length()); // NullPointerException

} catch (NullPointerException exception) {

System.out.println("NullPointerException caught: " + exception.getMessage());

}



Comments