Exceptions
A syntax error prevents Python from understanding a program. An exception happens while valid code runs, such as converting 'ten' to a number or dividing by zero. A try block surrounds an operation that may fail; a matching except block handles the specific error.
Catch expected runtime errors and return useful messages without hiding unrelated bugs.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Exceptions
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Even a program with valid Python syntax can fail while it runs. Imagine a small calculator that receives two values as text. Ten and two are easy to convert to numbers, but the word ten is not. A zero denominator is a different problem: conversion works, but division fails. We want our calculator to explain those two expected failures instead of stopping with an unexplained traceback. In this lesson we will build a safe divide function, test the successful path and both error paths, and learn why specific exception handling is better than catching everything. Before seeing the code, predict the three results for ten divided by two, the word ten divided by two, and ten divided by zero.
- 00:46
The first should be five point zero. The other two should produce different messages that tell us what went wrong. First separate two kinds of failure. If we leave out a colon after an if statement, Python cannot parse the program; that is a syntax error. An exception is raised while valid code runs. In our function, float can raise ValueError when a string does not represent a number. The division can raise ZeroDivisionError when the converted denominator is zero. Put the conversion and division inside a try block. If both complete successfully, return the numeric quotient. Put an except ValueError branch after the try and return the message invalid number.
- 01:30
Put another branch for ZeroDivisionError and return cannot divide by zero. Now test each path. The strings ten and two contain valid numeric text, so float produces ten point zero and two point zero. The division returns five point zero. When the first string is the word ten, float raises ValueError before the division happens. Python looks for a matching except branch and returns invalid number. When the denominator string is zero, float converts it successfully, but the division raises ZeroDivisionError, so the other branch returns cannot divide by zero. These branches have different names because they represent different causes and usually need different remedies.
- 02:15
A user can correct an invalid number or choose a nonzero denominator. It is worth checking exactly which line can raise each error. If your try block contains too many unrelated operations, a ValueError from another operation may be caught and reported as a numeric entry problem even when it has a different cause. The website's deeper guide demonstrates a narrower try around a conversion. It puts the normal next step in an else block. Else runs only if the try finishes without an exception. It also uses finally to show that a final message runs on both success and failure. Finally is often useful for cleanup, though a with block is generally clearer for managing a file.
- 03:00
Run that example with invalid text, then change the text to twelve. Predict whether the else message appears and whether the finally message appears. Another deeper example handles a missing configuration value. Looking up a required dictionary key may raise KeyError. If a missing value is expected, dict get with a default can be simpler than catching an exception. If the value is required, a specific KeyError handler can return a useful message. This is a design choice based on meaning, not a rule that every error must be swallowed. The final guide example shows an intentional ValueError raised for a negative age.
- 03:42
Raising an exception gives the caller a clear signal that an input broke the function's contract. We should not return a fake age or continue calculations with invalid data. The caller can decide how to display the error or ask for another value. Exception handling becomes easier when we state what inputs are valid, which failures are expected, and who is responsible for explaining them. For this first exercise, our function has two expected runtime failures and one successful numeric result. Keep those three paths visible while you code. A common mistake is catching ValueError and assuming it will also handle division by zero.
- 04:23
It will not; the exception's type is ZeroDivisionError. Run the zero-denominator example and read the exception name before choosing a handler. Another mistake is using a bare except because it appears to make every test stop crashing. That can hide misspelled variable names, wrong indexes, and other bugs that deserve attention. Catch the specific conditions your function can reasonably recover from. A third mistake is putting an entire long program inside try, then returning invalid number for any ValueError from anywhere inside it. Keep the protected work focused enough that the message remains honest.
- 05:04
Finally, remember that catching an exception does not fix the bad input. It gives your program a chance to respond clearly. In a real interface, the next step might be to ask the user for a different value. Pause and finish safe divide in the browser editor. Run the three cases shown in the lesson and predict the lines before you press Run. The valid strings should produce five point zero. The word ten should produce invalid number. A zero denominator should produce cannot divide by zero. Then try a decimal numerator such as seven point five with a denominator of two. That checks that the function is not limited to whole numbers.
- 05:46
Use the task checker after your own tests; it checks behavior rather than a hard-coded transcript. Take the three-question quiz to mark the lesson complete. For an extra challenge, move a conversion into a narrow try with else and finally, as the guide demonstrates, and predict which branches run when conversion fails. You can also write a small function that raises ValueError for an impossible input. The on-screen lesson link contains runnable guide examples, expected output, common mistakes, and a practical task with hints.
Understand the concept
Catch only the exceptions you expect. In this lesson, ValueError means numeric text could not be converted and ZeroDivisionError means the denominator was zero. Broad except clauses can hide errors you did not intend to handle.
The practice function accepts two strings because real input often begins as text. It converts them with float, divides, and returns a numeric result for valid input. For the two expected failures it returns a clear message instead of crashing.
- try runs code that may raise an exception
- except ValueError handles invalid numeric text
- except ZeroDivisionError handles a zero denominator
See it step by step
Read the code, predict the output, then compare it with the result.
01. Catch bad numeric text
try:
number = int("ten")
except ValueError:
print("Enter digits")Enter digitsint raises ValueError for this text, and the matching handler prints a useful prompt.
02. Catch division by zero
try:
print(8 / 0)
except ZeroDivisionError:
print("Choose a nonzero divisor")Choose a nonzero divisorThe handler catches only division by zero, so the program can continue.
03. Successful try skips except
try:
print(float("6") / 2)
except ValueError:
print("Invalid")3.0No ValueError occurs, so Python skips the except body.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Put only the risky operation in try
A try block should be narrow enough that a matching error has one clear meaning. If a large block contains several conversions and calculations, an except ValueError may catch a failure from a different line than the one you expected. Do the conversion inside try, put work that needs a valid value in else, and put any unconditional final message in finally.
The else block runs only when try finishes without an exception. The finally block runs whether conversion succeeds or fails; it is commonly used to release resources, though with open is usually clearer for files. This example prints the sequence so you can see the control flow. Change the text to '12' and predict which message disappears.
text = "not-a-number"
try:
number = int(text)
except ValueError:
print("Conversion failed")
else:
print(number * 2)
finally:
print("Attempt finished")Conversion failed
Attempt finished- int raises ValueError, so the matching except block runs.
- else is skipped, but finally still prints its message.
- With text set to '12', else prints 24 before finally.
Handle missing configuration deliberately
Not every failure is a bad number. Looking up a missing dictionary key raises KeyError. Sometimes a missing value is normal and you should use dict.get with a default; other times it means the configuration is incomplete and you should tell the caller. Decide which case applies instead of catching every exception and returning a vague message.
In this example, host is required, while port has a reasonable default. A specific KeyError handler gives a useful result for missing host. The example only formats port as text; a real network client would also need to validate its type and range before connecting. Try removing port from the first dictionary and predict the address.
def address(settings):
try:
host = settings["host"]
except KeyError:
return "Missing host"
port = settings.get("port", 8000)
return f"{host}:{port}"
print(address({"host": "localhost", "port": 9000}))
print(address({"port": 9000}))localhost:9000
Missing host- Square-bracket lookup requires host and raises KeyError if absent.
- get supplies 8000 only when optional port is absent.
- Remove port from the first call to observe the default.
Raise an error where the rule is known
Exceptions are not only accidents Python discovers. Your own function can raise one when it detects invalid input. The function knows the business rule; the caller knows how to respond. This separation keeps a reusable function from printing a warning or silently returning a fabricated value that later calculations might treat as real.
Choose an exception type and message that match the problem. ValueError fits a valid kind of argument with an unacceptable value. Catch it at the boundary where a person can correct the input. During development, avoid catching an error so broadly that unrelated bugs are disguised as ordinary validation failures. Try changing age to zero to follow the successful path.
def ticket_price(age):
if age < 0:
raise ValueError("Age cannot be negative")
return 5 if age < 18 else 10
for age in [12, -1, 20]:
try:
print(ticket_price(age))
except ValueError as error:
print(error)5
Age cannot be negative
10- The function rejects only the impossible negative age.
- The caller catches that specific error and continues to the next input.
- Set the middle age to zero and predict all three prices.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Inside try, convert with float and return top / bottom. Follow with two specific except clauses: ValueError and ZeroDivisionError. Each clause returns its matching message.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Catching the wrong exception
try:
print(4 / 0)
except ValueError:
print('Bad number')try:
print(4 / 0)
except ZeroDivisionError:
print('Cannot divide by zero')What happens: ZeroDivisionError still stops the program.
The except type must match the error that may be raised.
Using a bare except
try:
risky_code()
except:
print('Something failed')try:
number = float('bad')
except ValueError:
print('Invalid number')What happens: Unrelated bugs are hidden behind a vague message.
Catch an expected error by name so other failures remain visible.