Welcome to this comprehensive guide on Java Checked and Unchecked Exceptions! By the end of this lesson, you'll have a solid understanding of these important concepts. Let's dive in! š
An Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions enable you to create programs that can resolve problems and continue running instead of crashing.
In Java, Exceptions can be either Checked or Unchecked. Let's explore the differences and similarities between them.
Checked exceptions are subclasses of the Exception class that must be handled (either by catching them or declaring them in a method's throws clause). They are checked at compile-time and represent exceptions that are expected to occur due to programming errors or external conditions.
Example: IOException, SQLException
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
// Writing to a non-existent file
FileWriter fileWriter = new FileWriter("non_existent_file.txt");
fileWriter.write("Hello, World!");
fileWriter.close();
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
}
}
}š Note: Always catch the most specific exception possible.
Unchecked exceptions are subclasses of the RuntimeException class that don't need to be declared in a method's throws clause and are only checked at runtime. They represent exceptions that are caused by programming errors such as NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException.
Example: NullPointerException, ArrayIndexOutOfBoundsException
public class UncheckedExceptionExample {
public static void main(String[] args) {
String[] array = new String[3];
System.out.println(array[5]); // Unchecked exception: ArrayIndexOutOfBoundsException
}
}There are several ways to handle exceptions in Java:
Which of the following is an example of a Checked Exception?
That's it for this lesson! Stay tuned for more in-depth Java tutorials on CodeYourCraft. Happy coding! š