Exception Handling
Python - A Quick Start for existing Programers
2 min read
This section is 2 min read, full guide is 44 min read
Published Sep 16 2025, updated Aug 17 2026
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
Python
Python has a number of keywords associated with exception handling:
try→ block of code to test.except→ block of code that runs if an error occurs.else→ runs if no exception occurs.finally→ always runs (cleanup code, e.g., close file).raise→ manually raise an exception.
Catching Exceptions
Catch specific exceptions:
try: x = 1 / 0except ZeroDivisionError: print("Cannot divide by zero!")Catch multiple:
try: val = int("abc")except (ValueError, TypeError) as e: print("Error:", e)Catch all (not recommended unless logging/debugging):
try: risky_code()except Exception as e: print("Unexpected error:", e)Raising Exceptions
def check_age(age): if age < 0: raise ValueError("Age cannot be negative!") return ageBuilt-in Exceptions
Base Classes:
BaseException→ root of all exceptions.Exception→ base for most user errors.ArithmeticError→ base for numeric errors.LookupError→ base for indexing/key errors.
Common Everyday Exceptions:
Exception→ generic base exception.ValueError→ invalid value (e.g.,int("abc")).TypeError→ wrong type (e.g.,3 + "hi").NameError→ variable not defined.IndexError→ list index out of range.KeyError→ dict key not found.ZeroDivisionError→ divide by zero.AttributeError→ attribute doesn’t exist.FileNotFoundError→ missing file.IOError→ I/O error (alias ofOSError).ImportError→ module can’t be imported.ModuleNotFoundError→ specific import error.RuntimeError→ generic runtime error.StopIteration→ end of iterator.AssertionError→ failedassert.
Arithmetic Errors:
ArithmeticError(base)ZeroDivisionErrorOverflowError(number too large)FloatingPointError
Lookup Errors:
LookupError(base)IndexErrorKeyError
OS & System Exceptions:
OSError→ base for system errorsFileNotFoundErrorPermissionErrorTimeoutErrorEOFError→ end of input reached.KeyboardInterrupt→ Ctrl+C pressed.SystemExit→ raised bysys.exit().
Other Useful Ones:
MemoryError→ out of memory.NotImplementedError→ abstract method not implemented.IndentationError/TabError→ indentation problems.UnicodeError(and subclasses:UnicodeEncodeError,UnicodeDecodeError,UnicodeTranslateError).
Demonstrate exception handling
def demo_exceptions(): # Example 1: Simple try/except try: result = 10 / 0 except ZeroDivisionError: print("Error: division by zero") # Example 2: Catch multiple errors try: num = int("hello") # ValueError except (ValueError, TypeError) as e: print("Conversion error:", e) # Example 3: try/except/else try: num = int("42") except ValueError: print("Invalid number") else: print("Converted successfully:", num) # Example 4: try/finally try: f = open("test.txt", "w") f.write("Hello") except IOError as e: print("File error:", e) finally: f.close() print("File closed safely") # Example 5: raise your own exception try: age = -5 if age < 0: raise ValueError("Age cannot be negative") except ValueError as e: print("Custom exception caught:", e) # Example 6: Generic exception try: x = unknown_variable except Exception as e: print("Something went wrong:", e)demo_exceptions()