22 The Try/Except Structure: Catching Errors
Instead of letting these errors crash our program, we can handle them gracefully using try
and except
. Think of it like having a safety net for your code. Here’s the basic structure:
try:
# Code that might raise an error
except:
# Code to handle the error
Let’s make our previous examples better:
= "Magic"
scroll print("Attempting to access the 11th character...")
try:
= scroll[11]
last_letter print("The 10th letter is:", last_letter)
except:
print("The scroll text isn't long enough!")
print("The program continues running!")
This will output:
Attempting to access the 11th character...
The scroll text isn't long enough!
The program continues running!
22.1 The ‘as’ Keyword: Capturing Error Messages
When catching errors, the as
keyword lets us capture the actual error message. Think of it like catching a message in a bottle - the as
keyword lets us read what’s inside:
# Without using 'as'
try:
= int("not a number")
magic_number except ValueError:
print("There was an error") # Generic message
# Using 'as' to get the specific error message
try:
= int("not a number")
magic_number except ValueError as error:
print(f"Specific error: {error}") # Shows the actual error message
You can use different names after as
:
try:
= int("abc")
number except ValueError as problem:
print(f"Problem occurred: {problem}")
22.2 The Raise Statement: Creating Our Own Errors
Sometimes we want to create our own errors when certain conditions aren’t met. The raise
statement lets us do this. Think of it like raising a red flag to signal that something is wrong:
= "Dragons " * 30 # A very long text
scroll_text
try:
if len(scroll_text) > 100:
raise ValueError("Scroll is too long to be read safely!")
print(f"The scroll says: {scroll_text}")
except ValueError as error:
print(f"Error: {error}")
This will output:
Error: Scroll is too long to be read safely!
22.3 Common Exception Types
Python has several built-in exception types we can use:
ValueError
: When a value is the right type but wrong valueTypeError
: When an operation is performed on an incompatible typeIndexError
: When trying to access a non-existent indexRuntimeError
: When an error doesn’t fit into any other category
Let’s see them in action:
# ValueError example
= []
ingredients try:
if len(ingredients) < 2:
raise ValueError("At least two ingredients are needed!")
print("Ready to brew potion!")
except ValueError as error:
print(f"Error: {error}")
# TypeError example
= "maximum"
spell_power try:
if not isinstance(spell_power, int):
raise TypeError("Spell power must be a number!")
print("Valid spell power!")
except TypeError as error:
print(f"Error: {error}")
22.4 Practice Time: Error Handling Quests
Now it’s your turn to practice error handling. Try these challenges:
- Create code that tries to convert “one hundred” to a number and handles the error:
= "one hundred"
magic_number try:
= int(magic_number)
result print(f"The number is: {result}")
except ValueError as error:
print(f"Error: That's not a proper number!")
print(f"Actual error message: {error}")
- Write code that raises an error if a magic spell is too short:
= "x"
spell_name try:
if len(spell_name) < 2:
raise ValueError("Spell name must be at least 2 letters long!")
print(f"Casting spell: {spell_name}")
except ValueError as error:
print(f"Error: {error}")
22.5 Common Bugs to Watch Out For
As you practice error handling, be wary of these common pitfalls:
Catching all errors: Using bare
except:
without specifying an error type can hide bugs. It’s better to catch specific errors.Unclear error messages: When raising exceptions, make your error messages descriptive and helpful.
Missing the ‘as’ variable: If you use
as
to capture an error, make sure to use the error variable in your except block.Raising the wrong exception type: Use the most appropriate exception type for the situation.
22.6 Conclusion and Further Resources
Congratulations! You’ve now learned how to handle errors gracefully in Python. You can:
- Catch errors with
try
/except
- Capture error messages with
as
- Create your own errors with
raise
These skills will help you write programs that can deal with unexpected situations without crashing.
To learn more about error handling in Python, check out these resources:
- Python’s official documentation on Errors and Exceptions
- Real Python’s Python Exceptions Guide
- W3Schools Python Try Except
Remember, handling errors well is just as important as writing the code in the first place. Keep practicing these techniques, and your programs will become more reliable and user-friendly!