1 min read

Error Handling

Error handling is the process of anticipating, detecting, and resolving programming, application, and communications errors. It prevents the program from crashing and allows for graceful recovery or logging.

1. The Try-Catch Block

The core mechanism for handling runtime errors is the try-catch block.

  • Try: Contains the code that might throw an exception.
  • Catch: Contains the code that executes if an exception occurs.

JavaScript / Java / C++

try {
    // Code that might fail
    let result = riskyOperation();
} catch (error) {
    // Code to handle the error
    console.error("Something went wrong:", error);
}

Python

Python uses try and except.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"An error occurred: {e}")

2. The Finally Block

The finally block contains code that will always execute, regardless of whether an error occurred or not. It is typically used for cleanup (closing files, database connections).

try {
    openFile();
    readFile();
} catch (e) {
    handleError(e);
} finally {
    closeFile(); // Always runs
}

3. Throwing Exceptions

You can manually trigger an error using the throw (or raise in Python) keyword.

  • JavaScript: throw new Error("Something bad happened");
  • Python: raise ValueError("Invalid value")
  • Java: throw new IllegalArgumentException("Invalid argument");

programming/control-flow programming/common-syntax