Free preview
100 lessons
Python Done Right
Free preview
Python Done Right · 100 lessons
No surprise gaps
Actually remember it
Skip what you know
One subscription. All learning paths included.
Our content is best on a larger screen
try-exceptWhat exceptions are
When we write code, some errors only reveal themselves when the program actually runs. These are called exceptions - unexpected situations that Python cannot handle automatically.
Consider this code:
age = int("twenty")
Python cannot convert the string "twenty" into an integer. There is no sensible way for it to proceed, so it raises an exception and the program crashes.
Tip
Exceptions often arise from data rather than faulty code. Our programs interact with the real world - reading files, receiving network responses, processing information - and that data is not always what we expect.
If an exception is not handled, our program stops immediately. Any code after the error never runs:
print("Starting program...")
result = 10 / 0
print("Finishing program...") # This line never executes
The first print() executes, but when Python encounters the division by zero it raises a ZeroDivisionError and terminates. The final print() is never reached.
When an exception occurs, Python displays a traceback - a report showing what went wrong. Here we walk through one.
print("Starting program...")
result = int("hello")
print("Finishing program...")
Running this produces:
Starting program...
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'hello'
The key information is in the last line - the exception type and message:
ValueError - the type of exception (Python received a value it could not work with)invalid literal for int() with base 10: 'hello' - the message explaining what went wrongNotice that "Starting program..." was printed, but "Finishing program..." was not - the program crashed on line 2 before reaching line 3.
Tip
Tracebacks can look noisy, but the key is to start from the bottom - that is where Python reports the specific error type and message - then work upwards to see the chain of calls that led there.
Details
Practice questions
4 questions
Which statement best describes why exceptions occur?
Select the correct answer:
+ 3 more questions
Basic try-except syntax
When errors can occur, we can handle them instead of letting the program crash. Python gives us the try-except statement for this.
We place the risky code inside a try block. If that code runs without problems, the except block is skipped. But if an exception is raised, Python jumps immediately to the except block and runs that instead:
try:
risky_operation()
except:
handle_the_error()
Control never returns to the try block once an error happens - execution continues after the whole try-except statement.
Here is a concrete example showing how the flow works:
print("Starting program...")
try:
x = int("hello") # This line raises an exception
print("Converted successfully!")
except:
print("Something went wrong!")
print("Finishing program...")
Starting program...
Something went wrong!
Finishing program...
The program does not crash. When int("hello") raises an exception, Python jumps to the except block. After handling the error, the program continues past the try-except statement - so "Finishing program..." still prints.
Tip
Only the code inside the try block is protected. Statements before or after it are unaffected, so we can tightly isolate just the operations we expect might fail.
Here we use try-except to handle invalid user input gracefully.
try:
user_input = input("Enter a number: ")
number = int(user_input)
print("You entered:", number)
except:
print("That wasn't a valid number.")
Case 1: Valid input
Enter a number: 42
You entered: 42
int("42") succeeds, so the except block is skipped entirely.
Case 2: Invalid input
Enter a number: hello
That wasn't a valid number.
int("hello") raises a ValueError. Python jumps immediately to the except block, prints the message, and continues safely - no crash.
We can use this pattern any time we want to recover from runtime errors: retrying an operation, providing a default value, or logging the problem instead of crashing.
Tip
Good error handling is about control, not silence. We decide what happens when something goes wrong, instead of letting the program abort unexpectedly.
Practice questions
4 questions
In the Python Editor, write a function called safe_int(text) that:
text to an integer and return it.0.The function must use a try-except block.
After writing it, running the code will output a token used to check your work - what is the token?
Select the correct answer:
+ 3 more questions
Catching specific exception types
We have seen how try-except prevents a program from crashing. However, not all exceptions mean the same thing - and catching everything can make debugging harder.
Consider this code:
try:
result = int("hello")
except:
print("Something went wrong!")
This works, but it is too broad. If any error happens inside the try block - even one we did not expect - it will be caught and silently handled. That can hide real bugs such as missing variables, typos, or logic errors.
Instead, we can catch only the exception type we expect by naming it after except:
except ValueError:
This tells Python to handle only ValueError exceptions and let anything else through.
Different errors in Python have different types:
ValueError - a function receives an inappropriate value (e.g. int("hello"))TypeError - an operation is applied to the wrong type (e.g. "hi" + 5)Details
Here we see how catching a specific exception type changes the behaviour depending on which error occurs.
try:
text = "hello"
number = int(text)
total = number + "5" # This line causes a TypeError
except ValueError:
print("Couldn't convert to an integer.")
int("hello") raises a ValueError. The except ValueError: clause matches, so Python prints Couldn't convert to an integer. and continues normally.
Now consider a slight variation:
try:
text = "5"
number = int(text)
total = number + "5" # Wrong type: int + str
except ValueError:
print("Couldn't convert to an integer.")
This time int("5") succeeds - no ValueError. But number + "5" raises a TypeError. Since our handler only catches ValueError, Python does not intercept it and the program crashes with a traceback:
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Tip
By catching only the errors we expect (ValueError), we allow truly unexpected ones (TypeError, NameError, etc.) to surface. This keeps subtle bugs visible instead of burying them under a generic error message.
Practice questions
4 questions
In the Python Editor, write a function called safe_divide(a, b) that:
a / b for normal division."undefined" only when dividing by zero (ZeroDivisionError).Once done, running the code will output a token used to verify your implementation. What is the token?
Select the correct answer:
+ 3 more questions