Skip to content

Exception handling

Exception Handling: Dealing with Errors

In programming, an Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Essentially, it's a "crash" or an "error."

Why handle Exceptions?

  1. Prevent Crashing: If an error occurs (like dividing by zero), you don't want the whole program to just stop.
  2. User Experience: Instead of a cryptic computer error, you can show a friendly message (e.g., "Please enter a valid number").
  3. Cleanup: Ensure that things like files or database connections are closed even if an error occurs.

The "Try-Catch" Logic

  • Try: "Try running this code."
  • Catch/Except: "If an error happens, do this instead."
  • Finally: "No matter what happens, always do this at the end."

Logic First

Exception handling is about defensive programming. You are anticipating what could go wrong and providing a safety net.