๐จ 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?
- โ ๏ธ Common Python Errors
- ๐ ๏ธ try / except
- ๐ฆ Catching Specific Exceptions
- ๐ else
- ๐งน finally
- ๐จ Raising Exceptions
- ๐๏ธ Custom Exceptions
- ๐ฎ Real 42 Examples
- โ ๏ธ Common Beginner Mistakes
- ๐ Best Practices
- ๐ Final Notes
๐ 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
finallyfor 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.