β οΈ 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
finally
or use try-with-resources - β Use custom messages for debugging clarity
- β οΈ Avoid empty
catch
blocks β 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 :