What is a Try-Catch Block?
A try-catch block is used to handle exceptions gracefully in Java.
It allows you to run risky code in the try block, and catch any exceptions that may occur.
⚠️ It prevents the program from crashing and gives control to the developer on what to do if something goes wrong.
🔧 Syntax
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}✅ Example
public class Main {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}Error: Division by zero is not allowed.🔁 Multiple Catch Blocks
You can handle different types of exceptions separately:
try {
int[] arr = new int[3];
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Math error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is invalid");
}🧠 Java checks catch blocks from top to bottom, so always catch specific exceptions first.
🔄 Nested Try-Catch
You can also nest try-catch blocks to handle exceptions independently:
try {
System.out.println("Outer try");
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch: Division by zero");
}
} catch (Exception e) {
System.out.println("Outer catch");
}Outer try
Inner catch: Division by zero🔍 Best Practices
Catch the most specific exception first
Use Exception only when you don’t know which one might occur
Avoid empty catch blocks (
catch(Exception e) {}) — always handle or log the exceptionDon’t use
try-catchto control normal flow (not a substitute forif)
🧾 Recap
Keyword | Purpose |
|---|---|
| Run code that might throw an error |
| Handle the error if it occurs |
| Exception object holding the error |