← Back to Chapters

Java Exception Handling

⚠️ Java Exception Handling

? Quick Overview

Exception Handling in Java is a powerful mechanism that allows a program to handle runtime errors gracefully. Instead of crashing the program, Java provides structured ways to detect, catch, and respond to unexpected situations.

? Key Concepts

  • An exception is an abnormal event that disrupts normal program flow
  • Exceptions occur at runtime
  • Java uses try, catch, finally, throw, and throws
  • All exceptions are part of the Throwable hierarchy

? Syntax & Theory

Java wraps risky code inside a try block and handles errors using one or more catch blocks. Optional cleanup code goes inside finally.

? View Code Example
// Basic try-catch syntax in Java
try {
int a = 10;
int b = 0;
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}

?️ Interactive Lab: Exception Simulator

Enter two numbers to simulate Java's ArithmeticException handling.
Try entering 0 as the second number!

int result = / ;
// Console output awaiting execution...

? Code Example

? View Code Example
// Handling an exception with finally block
try {
int[] nums = {1, 2, 3};
System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range");
} finally {
System.out.println("Execution completed");
}

? Live Output / Explanation

When an exception occurs, Java immediately transfers control to the matching catch block. The finally block always executes, whether an exception occurs or not.

? Tips & Best Practices

  • Always catch specific exceptions instead of generic ones
  • Use finally for cleanup code like closing files
  • Never suppress exceptions silently
  • Keep try blocks small and focused

? Try It Yourself

  • Modify code to handle NullPointerException
  • Add multiple catch blocks
  • Remove the exception and observe normal flow
  • Create your own custom exception class