Jump to content

3.6.2 Exception Handling (try-catch)

From Computer Science Knowledge Base

3.6.2 Exception Handling (try-catch)

Imagine you're a robot trying to open a file on a computer. What if the file isn't there? Instead of just stopping and saying "Error!", you want the robot to be polite and say, "I couldn't find the file, would you like me to try again?"

Exception Handling is a programming technique that allows your program to gracefully deal with runtime errors (also called "exceptions"). Instead of crashing when something unexpected happens, you can "catch" the error and tell your program what to do about it.

The most common way to do this is using a try-catch block (or try-except in Python).

How try-catch Works:

  1. try block:
    • You put the code that might cause an error inside the try block.
    • It's like saying, "TRY to do this risky thing."
  2. catch block (or except in Python):
    • If an error (an "exception") does happen inside the try block, the program immediately jumps to the catch block.
    • The catch block contains the code that tells your program how to handle the error. This might involve:
      • Printing an error message to the user.
      • Logging the error for the programmer to see later.
      • Trying an alternative action.
      • Asking the user for new input.
    • You usually specify the type of error you want to catch (e.g., a "file not found" error, or a "division by zero" error).

Example (Java concept):

// Imagine we're trying to divide two numbers
int numerator = 10;
int denominator = 0; // Uh oh, this will cause a division by zero error!

try {
    // TRY to do this calculation
    int result = numerator / denominator;
    System.out.println("Result: " + result); // This line won't run if an error happens above
} catch (ArithmeticException e) { // CATCH a specific type of error: ArithmeticException (like division by zero)
    // If the error happens, do THIS instead of crashing
    System.out.println("Error: Cannot divide by zero!");
    // You can also print details about the error:
    // System.out.println("Error details: " + e.getMessage());
}

System.out.println("Program continues after the try-catch block.");
// Output:
// Error: Cannot divide by zero!
// Program continues after the try-catch block.

Without the try-catch block, the program would have crashed when it tried to divide by zero. With it, it handles the error gracefully and continues running.

Exception handling is a powerful way to make your programs more robust and user-friendly, preventing unexpected crashes and providing helpful feedback.

Bibliography: