Skip to content

Python 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.

Try ... Except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
  print(x)
except:
  print("An exception occurred")

Since the variable x is not defined, the program will jump to the except block instead of crashing.

The else Keyword

You can use the else keyword to define a block of code to be executed if no errors were raised:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Specific Exceptions

It's better to catch specific errors rather than a general except:.

try:
    # code
except ZeroDivisionError:
    print("You cannot divide by zero!")