πŸ“š Java Reference
Estimated reading: 3 minutes 424 views

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, and throw/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?
ErrorsSerious issues (e.g., memory leaks, JVM crashes) Not usually recoverable
ExceptionsProblems 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
IOExceptionInput/Output error (files, streams)
SQLExceptionDatabase query failure
ClassNotFoundExceptionClass not found during runtime

Must be handled with try-catch or declared with throws


Unchecked Exceptions (Runtime)

Exception Cause
NullPointerExceptionAccessing a null object
ArrayIndexOutOfBoundsExceptionInvalid array index
ArithmeticExceptionDivision by zero
IllegalArgumentExceptionInvalid 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 :
Share

Java Errors & Exceptions

Or Copy Link

CONTENTS
Scroll to Top