Exceptions in Java
In Java, exceptions are unexpected events or errors that occur during the execution of a program. They disrupt the normal flow of the program and must be handled to ensure the application runs smoothly.
What is an Exception?
- An exception is an object that represents an error or unexpected condition.
- It is generated (“thrown”) when an error occurs and can be “caught” and handled by the program.
Hierarchy of Exceptions
- All exceptions in Java are part of the
java.lang.Exception
class, which is a subclass ofThrowable
. - The main branches of the exception hierarchy:
- Checked Exceptions: Checked at compile time.(e.g.,
IOException
,SQLException
) - Unchecked Exceptions: Not checked at compile time. (e.g.,
NullPointerException
,ArithmeticException
) - Errors: Serious problems that applications should not try to handle (e.g.,
OutOfMemoryError
).
- Checked Exceptions: Checked at compile time.(e.g.,
Syntax for Exception Handling
Java provides the try-catch-finally
block for handling exceptions.
Basic Structure
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Optional block, executed regardless of exception
}
Example: Division by Zero
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("End of program.");
}
}
}
Output:
Error: Cannot divide by zero!
End of program.
Key Features of Exception Handling
- Prevents Program Crashes: Allows you to handle errors gracefully.
- Improves Readability: Centralizes error-handling code.
- Ensures Resource Management: Use the
finally
block ortry-with-resources
for cleanup.
Checked and Unchecked Exceptions in Java
Checked Exceptions
- Definition: Exceptions checked at compile time by the compiler.
- Examples:
IOException
SQLException
ClassNotFoundException
- Use Case: Used for predictable errors like file handling or database operations.
Example:
import java.io.*;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent-file.txt");
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
Unchecked Exceptions
- Definition: Exceptions not checked at compile time. They occur at runtime.
- Examples:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
- Use Case: Typically caused by programming errors or logic mistakes.
Example:
public class UncheckedExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
}
}
Example: File Read
var filePath = "test.txt"; // Path to your file
var maxRetries = 3; // Maximum number of retries
var retryCount = 0; // Counter for retries
var success = false;
while (retryCount < maxRetries && !success) {
try {
System.out.println("Attempting to read the file (Attempt " + (retryCount + 1) + ")...");
var fileReader = new FileReader(filePath);
var bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
success = true;
System.out.println("File read successfully.");
} catch (IOException e) {
retryCount++;
System.out.println("Error reading file: " + e.getMessage());
if (retryCount < maxRetries) {
System.out.println("Retrying...");
try {
Thread.sleep(1000); // Pause before retrying
} catch (InterruptedException ie) {
System.out.println("Retry interrupted: " + ie.getMessage());
break;
}
} else {
System.out.println("Max retries reached. File read failed.");
}
}
}
This program is designed to read a file named test.txt
while making sure that it can handle errors smoothly if something goes wrong. If the file isn’t available or an issue arises, the program doesn’t give up right away. Instead, it tries up to three times to read the file, giving a short break (1 second) between each attempt. This way, there’s time to fix the problem, like adding the file to the correct location.
How it works: The program repeatedly tries to open and read the file line by line. If it succeeds, it prints the content, marks the task as completed, and stops trying further. But if it encounters an error (like the file not being found), it catches the issue, logs a helpful message, and prepares to retry. After three unsuccessful attempts, it informs the user that the process has failed and exits gracefully without crashing.
This approach ensures that the program remains reliable and user-friendly. It communicates what’s happening at each step, handles resources like file readers carefully, and avoids overwhelming the system by pausing briefly before retrying. It’s a thoughtful way to deal with temporary problems while keeping things running smoothly.
Check out the video for a detailed explanation: