Welcome to our comprehensive guide on Java Exception Hierarchy! This tutorial is designed to help both beginners and intermediates understand the fundamentals of exceptions in Java. Let's dive right in!
Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions. In Java, exceptions are handled to ensure the program doesn't crash but continues to run smoothly.
Checked Exceptions: These are exceptions that must be handled either by catching them in a try-catch block or by declaring them in the method signature. Examples include IOException and SQLException.
Unchecked Exceptions: These exceptions are not required to be caught or declared. They are further divided into Error and RuntimeException. Error is for errors that might occur during the execution of the program, and RuntimeException includes exceptions like NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException.
The exception hierarchy in Java is a tree-like structure that shows the relationships between different types of exceptions. The Throwable class is the superclass for all exceptions in Java.
Throwable
|
Exception
|
|------------RuntimeException
| |
| Error
| |
| |---------------...
|
|------------CheckedException
| |
| |---------------...Handling exceptions in Java involves three keywords: try, catch, and finally.
The try block is used to enclose the code that might throw an exception. The catch block is used to handle the exception. If an exception occurs within the try block, the program control is transferred to the appropriate catch block.
try {
// code that might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
}The finally block is optional and is used to release resources acquired in the try block, regardless of whether an exception occurred or not.
try {
// code that might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code to release resources
}RuntimeExceptionpublic class ExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
try {
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}
}
}CheckedExceptionimport java.io.FileReader;
import java.io.IOException;
public class ExceptionExample {
public static void main(String[] args) {
try (FileReader fileReader = new FileReader("file.txt")) {
int c;
while ((c = fileReader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.err.println("Error reading the file!");
}
}
}Which type of exception is not required to be handled?
This marks the end of our Java Exception Hierarchy tutorial. We hope you found it helpful! Keep coding and learning with CodeYourCraft. 💡📝🎉