Thuta Learning
AdvancedProgrammingbeginner

Exceptions (Try...Catch)

Relax. We'll talk through this in plain words — no textbook voice.

Exception handling is how you keep the whole program from crashing when an error happens at runtime. You put code that might error inside a try block, and if an error occurs, catch handles it. finally runs whether or not an error happened.

java
public class Main {
  public static void main(String[] args) {
    try {
      int[] numbers = {10, 20, 30};
      System.out.println(numbers[5]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Invalid index. Please choose an item inside the array.");
    } finally {
      System.out.println("Array check finished.");
    }
  }
}

The array only has indexes 0, 1, and 2, but calling numbers[5] triggers an exception. The catch block catches the error and prints a user-friendly message.

You should see
Invalid index. Please choose an item inside the array. Array check finished.

Real-World Use

Without exception handling, things like file reading, API calls, database queries, payment requests, and parsing user input can easily crash a production app.

Easy traps

  • Wrapping every bit of code that could error in a catch without checking what actually went wrong makes debugging harder. Make your error messages meaningful.
Exceptions (Try...Catch) | Thuta Learning