Java Exceptions

⚠️ Java Exceptions – try...catch

An exception is an event that disrupts the normal flow of a program. Exceptions usually occur during runtime — like dividing by zero, accessing invalid array indices, or opening a missing file.

To prevent a program from crashing, we use exception handling with:

try { ... } catch(Exception e) { ... }

🧩 Syntax

try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

✔️ Example 1: Handling Division by Zero

public class ExceptionExample {
public static void main(String[] args) {
try {
int num = 10;
int result = num / 0; // Exception occurs
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
System.out.println(“Program continues…”);
}
}

Output:

Error: Cannot divide by zero!
Program continues...

✔️ Example 2: Catching Multiple Exceptions

You can handle different exceptions separately.

public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]); // Array index error
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index!");
}
}
}

✔️ Example 3: Using a General Exception Catch

Sometimes exact exception type may not be known, so we catch all exceptions:

public class GeneralCatchExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

✔️ Example 4: Try-Catch with finally

finally block runs whether exception occurs or not — useful for closing resources.

public class FinallyExample {
public static void main(String[] args) {
try {
int result = 100 / 2;
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Something went wrong!");
} finally {
System.out.println("Finally block executed!");
}
}
}

🚀 Why Use Try…Catch?

Without Exception Handling With Try…Catch
Program crashes Program continues safely
No error control Errors handled gracefully
Bad user experience Better user experience

🧠 Real-Life Analogy

Try-catch works like:

  • try: “I’ll try opening this jar”

  • catch: “If I can’t, I’ll use a jar opener”

  • finally: “No matter what, I’ll put the jar back in the cupboard.”


Summary:

Term Meaning
try Code that may cause an error
catch Handles the error if it happens
finally Executes always
Exception Runtime error

You may also like...