🔥 Java Exception and Error Handling

Java Exceptions and Errors

Java Exceptions and Errors

⚠️ What is an Exception?

An exception is an event that disrupts the normal flow of a program. It occurs during runtime and is recoverable.

Example: Dividing by zero, accessing an invalid array index.

❌ What is an Error?

An error is a serious issue beyond the control of the application. Typically unrecoverable and leads to program termination.

Example: Hardware failure, memory issues, JVM crash.

🌳 Java Exception Hierarchy

All exceptions and errors inherit from the Throwable class:

Throwable
├── Exception       → Can be handled by code
│   ├── Checked     → Must be handled
│   └── Unchecked   → Optional to handle
└── Error           → Cannot/should not be handled
    

🧱 Types of Exceptions

✅ Built-in Exceptions

Predefined by Java. Handle common runtime issues.

Examples: NullPointerException, IOException, ArrayIndexOutOfBoundsException

🧑‍💻 User-defined Exceptions

Created by developers for specific logic. Extend the Exception class.

🔍 Built-in Exception Categories

✔️ Checked Exceptions

  • Checked at compile time
  • Must be handled using try-catch or declared with throws
  • Examples: IOException, SQLException, FileNotFoundException

❗Unchecked Exceptions

  • Not checked at compile time
  • Usually caused by bugs
  • Subclasses of RuntimeException
  • Examples: NullPointerException, ArithmeticException

📌 Summary

Type Checked? Handling Required? Common Examples
Checked Yes (compile-time) Yes IOException, SQLException
Unchecked No (runtime) Optional NullPointerException, ArithmeticException
Error No Not Handled OutOfMemoryError, StackOverflowError

🕒 Synchronous vs Asynchronous Exceptions

Type When It Happens Example
Synchronous During code execution Divide by zero, null access
Asynchronous Outside code flow User termination, hardware failure

🔐 Exception Handling Blocks

  • try: Wraps risky code
  • catch: Handles the exception
  • finally: Always runs (for cleanup)
try {
    // Code that may throw exception
} catch (Exception e) {
    // Handle exception
} finally {
    // Cleanup code
}

🎯 throw vs throws in Java

Both throw and throws relate to exception handling, but they serve different purposes in syntax and behavior.

Aspect throw throws
Purpose Used to actually throw an exception Used to declare exceptions a method might throw
Location Inside a method or block In method signature
Syntax throw new IOException("File error"); public void readFile() throws IOException
Number of Exceptions One exception at a time Can declare multiple exceptions separated by commas
Checked? Runtime operation (throws the exception) Compile-time declaration (required for checked exceptions)

✅ Example Using throw:

if (user == null) {
    throw new NullPointerException("User not found");
}

✅ Example Using throws:

public void processFile(String path) throws IOException {
    // Code that might throw IOException
}
Tip: Use throws in method declarations to signal potential risks. Use throw to trigger an exception when an actual issue occurs.

🧠 Catch Block Execution :

  • Only one catch block is executed per exception. Java stops checking once it finds a match.
  • Order matters: IOException (child) must appear before Exception (parent).
  • More specific = higher priority: Java matches the most specific exception type first.
  • Wrong order causes compile-time error: A child exception block after its parent is unreachable.
  • Top-down matching: Catch blocks are evaluated in the order written.
  • No match = program crash: If no block handles the exception, the JVM will terminate the program.
  • Throwable is the top-level class: Use catch (Throwable t) cautiously—this catches everything including fatal Errors.

✅ Correct Order Example:

try {
    // risky code
} catch (IOException e) {
    // handles IO problems
} catch (Exception e) {
    // handles any other exception
}

❌ Incorrect Order (Compile-Time Error):

try {
    // risky code
} catch (Exception e) {
    // this will catch all exceptions, including IO
} catch (IOException e) {
    // unreachable - compile error
}

🧠 Final Thoughts

  • Use exceptions to build robust code.
  • Understand Checked vs Unchecked exceptions.
  • Always clean up resources in finally.
  • Don't try to catch serious Errors like OutOfMemoryError.

🧠 Powered by Passion, Compiled with Precision

© 2025 JavaVerse Blog — Crafted by Janki Patel

💻 All things Java • Tutorials • Insights • Best Practices

Comments

Popular posts from this blog

Understanding How OOP Concepts Work with Real-Life Examples

🌿⚙️ Spring Boot Simplified