Skip to content

๐Ÿšจ Python Exceptions & Try/Except Guide

Beginner-friendly documentation about Python exceptions, error handling, try/except blocks, and debugging practices.

This document explains: - exceptions - errors - try - except - finally - else - custom exceptions - common debugging patterns


๐Ÿ“š Table of Contents


๐Ÿ“– What are Exceptions?

Exceptions are: - runtime errors - unexpected problems during execution

When an exception happens: - Python stops normal execution


Example

print(10 / 0)

Output:

ZeroDivisionError

Why Exceptions Matter

Exceptions help: - detect problems - avoid crashes - improve debugging - handle invalid data safely

Very important in: - parsers - APIs - MLX projects - file systems - user input validation


โš ๏ธ Common Python Errors

Exception Meaning
ValueError Invalid value
TypeError Wrong type
ZeroDivisionError Division by zero
FileNotFoundError File missing
KeyError Missing dictionary key
IndexError Invalid list index

๐Ÿ› ๏ธ try / except

try allows Python to: - attempt risky code

except handles: - the error safely


Example

try:
    number = int(input("Number: "))
except ValueError:
    print("Invalid number")

How It Works

Python: 1. runs the try block 2. checks for exceptions 3. jumps to except if an error happens


๐Ÿ“ฆ Catching Specific Exceptions

Good practice: - catch specific errors


Example

try:
    value = int("abc")

except ValueError:
    print("Conversion failed")

Avoid Catching Everything

Bad:

except:
    print("Error")

This hides: - debugging information - unexpected problems


Better Version

except ValueError:

๐Ÿ”„ else

else runs ONLY if: - no exception happened


Example

try:
    value = int("42")

except ValueError:
    print("Invalid")

else:
    print("Success")

๐Ÿงน finally

finally ALWAYS runs.

Even if: - exceptions happen


Example

try:
    file = open("test.txt")

except FileNotFoundError:
    print("Missing file")

finally:
    print("Finished")

Why finally is Useful

Useful for: - closing files - cleanup - freeing resources


๐Ÿšจ Raising Exceptions

You can manually create exceptions using:

raise

Example

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")

Why raise is Useful

Useful for: - validation - parsers - enforcing rules - debugging


๐Ÿ—๏ธ Custom Exceptions

You can create your own exception classes.


Example

class MapParserError(Exception):
    pass

Raising the Custom Exception

raise MapParserError("Invalid map format")

Why Custom Exceptions Matter

They help: - organize errors - improve debugging - create cleaner architecture

Very common in: - parsers - APIs - game engines


๐ŸŽฎ Real 42 Examples

Config Validation

if width <= 0:
    raise ValueError("Width must be positive")

Missing File

except FileNotFoundError:

Parser Error

class ConfigError(Exception):
    pass

Invalid Coordinates

raise MapParserError(
    "Invalid coordinates"
)

โš ๏ธ Common Beginner Mistakes

โŒ Catching All Exceptions

Bad:

except:

Too broad.


โŒ Ignoring Exceptions

Bad:

except ValueError:
    pass

Can hide bugs.


โŒ Using Exceptions for Normal Logic

Exceptions should handle: - unexpected problems

Not: - normal flow control


โŒ Forgetting finally Cleanup

Files/resources may remain open.


๐Ÿ“š Best Practices

  • Catch specific exceptions
  • Use meaningful error messages
  • Create custom exceptions for large projects
  • Avoid empty except
  • Keep exception handling readable
  • Use finally for cleanup

๐Ÿง  Why Exceptions Matter

Good exception handling helps: - debugging - reliability - maintainability - cleaner architecture

Exceptions become essential in: - parsers - file systems - APIs - MLX projects - validation systems


๐Ÿ“š Final Notes

Understanding exceptions is one of the most important Python skills.

Good error handling creates: - safer applications - cleaner debugging - better architecture - more maintainable projects

Strong exception handling becomes increasingly important in larger projects.