Exceptions
Learn to detect, catch, and manage errors gracefully so your programs never crash unexpectedly.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
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.
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.
Wrap risky code in a try block. If an error occurs, the except block handles it.
Always catch specific exception types. This is the professional way.
Here are the exceptions you'll encounter most often:
You can handle different exceptions differently:
Or handle them together if the response is the same:
The else block runs only if NO exception occurred:
The finally block always runs, whether there was an error or not. Perfect for cleanup.
Use raise to trigger an exception yourself. This is useful for validating data.
A function that safely gets a number from user input:
Process a list of data, handling errors without stopping:
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):.