Python Docs

Python Try "Except" — Core Cheat Sheet

What is Exception Handling?

Exception handling prevents your program from crashing when something goes wrong. Python uses the try–except structure to catch and handle errors safely.

Purpose of Try–Except

  • try — Code that may cause an error
  • except — Runs when an error occurs

Basic Try–Except

If an error happens in try, the except block handles it.

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

Without Try–Except (Program Crashes)

Without exception handling, Python stops the program immediately.

print(x)  # Causes error because x is not defined

Catching Specific Exceptions

You can catch specific errors like NameError, ValueError, or TypeError. This helps you customize responses for different error types.

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Common Exceptions You Can Catch

Exception TypeMeaning
NameErrorVariable not defined
ValueErrorWrong value used
TypeErrorWrong data type used
ZeroDivisionErrorDivision by zero
FileNotFoundErrorFile does not exist
KeyErrorMissing dictionary key
IndexErrorList index out of range

Summary

  • try runs risky code
  • except catches the errors
  • Use specific exceptions for debugging
  • Prevents program crashes