Java Errors & Exceptions β Complete Guide with Examples & Best Practices (2025)
Introduction β Why Understanding Java Errors & Exceptions Is Crucial
In Java development, errors and exceptions are inevitable β from user input mistakes to null references and out-of-memory crashes. What separates beginner code from production-grade applications is how well you handle and recover from these runtime issues.
By the end of this article, youβll know:
- The difference between errors and exceptions
- The Java exception hierarchy
- How to use
try-catch,finally, andthrow/throws - Best practices to write reliable and readable error-handling code
What Are Java Errors and Exceptions?
Errors vs Exceptions
| Category | Definition | Handled by developer? |
|---|---|---|
| Errors | Serious issues (e.g., memory leaks, JVM crashes) | Not usually recoverable |
| Exceptions | Problems during execution (e.g., invalid input, missing files) | Yes β must be handled |
Java Exception Hierarchy
Object
βββ Throwable
βββ Error (unchecked)
β βββ OutOfMemoryError, StackOverflowError
βββ Exception
βββ CheckedException
β βββ IOException, SQLException
βββ RuntimeException (unchecked)
βββ NullPointerException, ArrayIndexOutOfBoundsException
Common Types of Java Exceptions
Checked Exceptions (Compile-Time)
| Exception | Meaning |
|---|---|
IOException | Input/Output error (files, streams) |
SQLException | Database query failure |
ClassNotFoundException | Class not found during runtime |
Must be handled with try-catch or declared with throws
Unchecked Exceptions (Runtime)
| Exception | Cause |
|---|---|
NullPointerException | Accessing a null object |
ArrayIndexOutOfBoundsException | Invalid array index |
ArithmeticException | Division by zero |
IllegalArgumentException | Invalid method parameter |
These can be handled, but the compiler doesnβt require it.
Java Exception Handling Syntax
1οΈβ£ try-catch Block
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Explanation: Prevents crash and provides a fallback.
2οΈβ£ try-catch-finally Block
try {
String text = null;
System.out.println(text.length());
} catch (NullPointerException e) {
System.out.println("Null pointer error!");
} finally {
System.out.println("Cleanup done.");
}
Output:
Null pointer error!
Cleanup done.
finally always executes, regardless of exceptions.
3οΈβ£ throw β Manually Raise Exception
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Underage not allowed");
}
}
Used to manually signal an exception.
4οΈβ£ throws β Declare Exception in Method Signature
public void readFile(String file) throws IOException {
FileReader fr = new FileReader(file);
}
Checked exceptions must be declared or caught.
Built-in Java Exceptions Examples
NullPointerException
String str = null;
System.out.println(str.length()); // Throws NPE
ArrayIndexOutOfBoundsException
int[] nums = {1, 2};
System.out.println(nums[5]); // Out of bounds!
NumberFormatException
String age = "abc";
int num = Integer.parseInt(age); // Invalid integer format
ClassNotFoundException
Class.forName("com.unknown.ClassName"); // Throws CNFE
Create Custom Exceptions
class InvalidAgeException extends Exception {
public InvalidAgeException(String msg) {
super(msg);
}
}
public void checkAge(int age) throws InvalidAgeException {
if (age < 18) throw new InvalidAgeException("Must be 18+");
}
Custom exceptions provide domain-specific error handling.
Best Practices for Handling Java Exceptions
- Catch specific exceptions first, then general
- Always clean up resources in
finallyor use try-with-resources - Use custom messages for debugging clarity
- Avoid empty
catchblocks β they hide problems - Prefer unchecked exceptions for programming bugs
- Use logging frameworks (e.g., Log4j, SLF4J) to track exceptions
Summary β Java Errors and Exceptions
Understanding Java errors and exceptions helps you:
- Prevent crashes and enhance reliability
- Deliver user-friendly feedback
- Write robust and clean error-handling code
- Handle file operations, database access, and edge cases gracefully
Proper exception handling is a must-have skill for every Java developer.
FAQs on Java Errors and Exceptions
Whatβs the difference between Error and Exception?
Error: Unrecoverable (e.g.,OutOfMemoryError)Exception: Can and should be handled
Are exceptions objects in Java?
Yes. All exceptions extend from the Throwable class, which extends Object.
Do I have to catch runtime exceptions?
No. But itβs good practice to handle them gracefully.
Can I have multiple catch blocks?
Yes. Use separate blocks for each exception type:
try { ... }
catch (IOException e) { ... }
catch (SQLException e) { ... }
What is finally used for?
To guarantee code execution (e.g., closing resources) after try-catch.
Share Now :
