Skip to content

๐Ÿšจ Exception Handling in Java โ€“ Making Your Code More Reliable

๐Ÿ”– Introduction

Even the best code can go wrong. A file might not be found, a number might be divided by zero, or user input could be invalid.

Java handles such unexpected events using Exception Handling โ€” a powerful feature to manage runtime errors and avoid crashes.


โ“ What is an Exception?

An exception is an event that disrupts the normal flow of the program. Java provides a way to catch and handle these gracefully.


๐Ÿ”น Types of Exceptions

TypeDescriptionExample
CheckedChecked at compile timeIOException, SQLException
UncheckedOccur during runtimeNullPointerException, ArithmeticException

๐Ÿงฏ try-catch Block โ€“ Handle It Gracefully


โœ… Syntax:

try {
    // code that might throw an exception
} catch (ExceptionType name) {
    // handle the exception
}

๐Ÿ“Œ Example: Divide by Zero

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // risky
        } catch (ArithmeticException e) {
            System.out.println("Can't divide by zero!");
        }
    }
}

๐Ÿ” finally Block โ€“ Always Executes

Used for cleanup actions like closing files or database connections.

try {
    // code
} catch (Exception e) {
    // handling
} finally {
    System.out.println("This always runs!");
}

๐Ÿš€ throw and throws โ€“ Custom and Propagated Exceptions


๐Ÿ”น throw โ€“ Throw an Exception Manually

public class AgeChecker {
    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Underage not allowed!");
        }
    }
}

๐Ÿ”น throws โ€“ Declare That a Method May Throw

public void readFile(String path) throws IOException {
    FileReader file = new FileReader(path);
}

๐Ÿ”จ Multiple catch Blocks

You can handle different exceptions separately:

try {
    String s = null;
    System.out.println(s.length());
} catch (NullPointerException e) {
    System.out.println("Null reference!");
} catch (Exception e) {
    System.out.println("Something went wrong!");
}

๐Ÿงช Challenge: Handle Array Index Exception

public class ArrayExample {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        try {
            System.out.println(nums[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds!");
        }
    }
}

๐Ÿง  Best Practices

  • Catch specific exceptions first.
  • Use finally to release resources.
  • Avoid catching Exception blindly unless absolutely necessary.

โœ… What You Learned

  • What exceptions are and why they matter
  • try, catch, finally, throw, and throws
  • Handling both built-in and custom exceptions

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *