πŸ“š Java Reference
Estimated reading: 3 minutes 33 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java Errors & Exceptions

Or Copy Link

CONTENTS
Scroll to Top