Exception Handling in Java

Chapter 9: Exception Handling in Java

Chapter 9: Exception Handling in Java

In Java, exception handling is a powerful mechanism to handle runtime errors, allowing the normal flow of the program to continue. Without proper exception handling, errors can lead to unexpected termination of the program.

๐Ÿ“Œ What is an Exception?

An exception is an event that disrupts the normal flow of a program’s execution. It is an object which is thrown at runtime.

Common Exception Types:

  • ArithmeticException – Divide by zero
  • NullPointerException – Accessing object with null reference
  • ArrayIndexOutOfBoundsException – Invalid index access
  • NumberFormatException – Invalid number parsing

๐Ÿงช Java Exception Hierarchy

All exceptions are subclasses of Throwable:

  • Throwable
    • Error
    • Exception
      • RuntimeException

๐Ÿ”ง Java Exception Handling Keywords

  • try – Code that might throw an exception
  • catch – Code to handle the exception
  • finally – Code that executes regardless of an exception
  • throw – Used to explicitly throw an exception
  • throws – Declares the exceptions a method might throw

๐Ÿ’ก Example: try-catch

public class Demo {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
}

๐Ÿงน finally Block

The finally block executes whether an exception is handled or not. It is often used to close resources like files or database connections.

Example:

try {
  int data = 50 / 0;
} catch (ArithmeticException e) {
  System.out.println("Exception caught");
} finally {
  System.out.println("finally block is always executed");
}

๐ŸŽฏ throw Keyword

The throw keyword is used to throw an exception explicitly.

throw new ArithmeticException("Divide by zero not allowed");

๐Ÿงพ throws Keyword

throws is used to declare exceptions in the method signature.

public void readFile() throws IOException {
  // file operations
}

๐Ÿงฐ Creating Custom Exceptions

We can create our own exception by extending Exception class:

class MyException extends Exception {
  MyException(String msg) {
    super(msg);
  }
}

✅ Benefits of Exception Handling

  • Improves code robustness
  • Enhances program readability
  • Prevents abrupt termination
  • Helps debugging and maintenance

๐Ÿ“˜ Chapter Summary

ConceptDescription
ExceptionRuntime error that disrupts program flow
try-catchHandle exceptions gracefully
finallyCleanup block executed always
throwUsed to throw custom exception
throwsDeclares exceptions in method

❓ FAQs with Answers

Q1: What is an exception in Java?

A: An exception is a runtime error that disrupts the normal flow of a program.

Q2: What are checked and unchecked exceptions?

A: Checked exceptions are checked at compile time (e.g., IOException). Unchecked exceptions occur at runtime (e.g., NullPointerException).

Q3: What is the use of finally block?

A: To ensure execution of important cleanup code, even if an exception occurs.

Q4: What’s the difference between throw and throws?

A: throw is used to throw an exception, throws is used to declare possible exceptions.

Q5: Can a method have multiple catch blocks?

A: Yes, to handle different types of exceptions separately.

Q6: What is a custom exception?

A: A user-defined class extending Exception to represent specific errors.

Q7: What happens if an exception is not caught?

A: Program terminates and displays the exception stack trace.

Q8: Can we have try block without catch?

A: Yes, only if a finally block is present.

Q9: How to catch multiple exceptions in one block?

A: From Java 7 onward, use pipe symbol (|):

catch (IOException | SQLException e) {}

Q10: Is it good to catch Exception class directly?

A: No, it’s not recommended as it hides specific exception causes.

๐Ÿ“Œ Related Links: Complete Java Course

๐Ÿ“Œ Related Links: Complete Java Course

Comments

Popular posts from this blog

Best AI Tools for Students and Professionals in 2025 | Boost Learning & Productivity

Introduction to Java

Top AI Tools for Content Creators: Bloggers, YouTubers & Writers (2025)