← Back to Chapters

Java try-catch

? Java try-catch

? Quick Overview

The try-catch mechanism in Java is used to handle runtime errors (exceptions) gracefully, preventing program termination and allowing controlled recovery.

? Key Concepts

  • try wraps risky code
  • catch handles the exception
  • Multiple catch blocks are allowed
  • Unchecked exceptions occur at runtime

? Syntax / Theory

Java executes code inside try. If an exception occurs, control immediately transfers to the matching catch block.

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

▶️ Code Example

? View Code Example
// Handling ArithmeticException in Java
public class TryCatchDemo {
public static void main(String[] args) {
try {
int a = 20;
int b = 0;
int c = a / b;
System.out.println(c);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
}
}

?️ Live Output / Explanation

When division by zero occurs, Java throws an ArithmeticException. The program does not crash; instead, the catch block executes and prints a message.

? Interactive Simulator

Enter numbers to simulate execution flow. Try dividing by 0!

try {
  int result = a / b;
}
catch (ArithmeticException e) {
  System.out.println("Error!");
}
> Console: Waiting for input...

? Tips & Best Practices

  • Catch specific exceptions instead of generic ones
  • Avoid empty catch blocks
  • Use meaningful error messages

? Try It Yourself

  • Handle ArrayIndexOutOfBoundsException
  • Add multiple catch blocks
  • Print exception details using e.getMessage()