Exceptions
Learn to detect, catch, and manage errors gracefully so your programs never crash unexpectedly.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
What Are Exceptions?
When something goes wrong in your Python code — like dividing by zero or opening a missing file — Python raises an exception . Without handling, your program crashes.
Why Handle Exceptions?
Without Exception Handling
With Exception Handling
Program crashes completely
Program continues running
Confusing error messages
User-friendly messages
Data might be lost
Data is saved safely
Resources left open
Resources cleaned up properly
The try-except Block
Wrap risky code in a try block. If an error occurs, the except block handles it.
Syntax
What It Does
try:
Code that might fail goes here
except:
Runs if an error occurs in try
Catching Specific Exceptions
Always catch specific exception types. This is the professional way.
Common Exception Types
Here are the exceptions you'll encounter most often:
Exception
When It Happens
Example
ValueError
Wrong value type
int("abc")
TypeError
Wrong operation for type
"5" + 3
ZeroDivisionError
Dividing by zero
10 / 0
IndexError
Invalid list index
my_list[100]
KeyError
Missing dictionary key
my_dict["name"]
FileNotFoundError
File doesn't exist
open("missing.txt")
NameError
Variable not defined
print(xyz)
Catching Multiple Exceptions
You can handle different exceptions differently:
Or handle them together if the response is the same:
Getting the Error Message
The else Block
The else block runs only if NO exception occurred:
Block
When It Runs
Always tries to run
Only if error in try
else:
Only if NO error in try
The finally Block
The finally block always runs, whether there was an error or not. Perfect for cleanup.
The Complete Structure
Raising Exceptions
Use raise to trigger an exception yourself. This is useful for validating data.
Common Mistakes to Avoid
Mistake
Problem
Fix
Catches everything, hides bugs
except ValueError:
Large try block
Hard to know what failed
Put only risky code in try
Empty except block
Error is silently ignored
At least log the error
Catching too high
except Exception catches all
Be specific about types
Not cleaning up
Files/connections left open
Use finally or with
Practical Example: Safe Number Input
A function that safely gets a number from user input:
Practical Example: Calculator
Practical Example: Data Processor
Process a list of data, handling errors without stopping:
Summary: Quick Reference
Keyword
Purpose
Code that might fail
try: x = 1/0
except Type:
Handle specific error
except Type as e:
Capture error message
except ValueError as e:
Runs if no error
else: print("OK")
finally:
Always runs (cleanup)
finally: file.close()
raise
Trigger an exception
raise ValueError("!")
Key Takeaways:
- • Always catch specific exception types
- • Use finally for cleanup that must always happen
- • Use else for code that should only run on success
- • Raise exceptions early when you detect invalid data
- • Never use bare except: in production code
What's Next?
You now know how to protect your programs from crashing and handle errors gracefully. Exception handling is essential for building reliable, professional Python applications.
Next up: Lesson 11 – Modules and Packages — Learn how to organize your code into reusable modules and use Python's powerful standard library.
Lesson 10 done — your programs are now crash-proof!
try/except, else, finally, raise — you know the full exception handling toolkit. This is what separates fragile scripts from professional, production-ready code.
🚀 Up next: Modules & Packages — discover Python's vast library ecosystem and learn to organise your own code into reusable files.
Practice quiz
Why does try/except exist?
- To make code run faster
- To catch errors so the program doesn't crash
- To define new variables
- To import modules
Answer: To catch errors so the program doesn't crash. try/except lets you handle errors gracefully so a problem doesn't crash the whole program.
Which exception is raised by int('hello')?
- TypeError
- KeyError
- ValueError
- IndexError
Answer: ValueError. Converting a non-numeric string with int() raises ValueError.
Which exception does accessing my_dict['age'] raise when that key is missing?
- KeyError
- IndexError
- NameError
- ValueError
Answer: KeyError. A missing dictionary key raises KeyError.
What does 10 / 0 raise?
- ValueError
- ZeroDivisionError
- ArithmeticError only
- Nothing, it returns infinity
Answer: ZeroDivisionError. Dividing by zero raises ZeroDivisionError.
When does the else block of a try statement run?
- Always
- Only if an exception occurred
- Only if NO exception occurred in try
- Never
Answer: Only if NO exception occurred in try. The else block runs only when the try block completed without raising an exception.
When does the finally block run?
- Only on success
- Only on error
- Always, whether or not an error occurred
- Only if there is no except block
Answer: Always, whether or not an error occurred. finally always runs — it's ideal for cleanup like closing files or connections.
How do you capture the error message in a variable named e?
- except ValueError -> e:
- except ValueError as e:
- except ValueError(e):
- except e = ValueError:
Answer: except ValueError as e:. Use 'except ValueError as e:' to bind the exception object to e.
Why is a bare 'except:' discouraged?
- It is slower
- It catches ALL errors and can hide bugs
- It is invalid syntax
- It only catches ValueError
Answer: It catches ALL errors and can hide bugs. A bare except catches everything, even unexpected errors, which can silently hide bugs.
How do you trigger an exception yourself for invalid data?
- throw ValueError('bad')
- raise ValueError('bad')
- error ValueError('bad')
- except ValueError('bad')
Answer: raise ValueError('bad'). The raise keyword triggers an exception, e.g. raise ValueError('Age cannot be negative!').
How can you handle ValueError and ZeroDivisionError the same way in one except?
- except ValueError, ZeroDivisionError:
- except (ValueError, ZeroDivisionError):
- except ValueError or ZeroDivisionError:
Answer: except (ValueError, ZeroDivisionError):. Group multiple exception types in a tuple: except (ValueError, ZeroDivisionError):.
Continue this course
- Previous: File Handling
- Next: Modules and Packages