Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python exceptions and error handling code

Practice handling specific exceptions, using else and finally, and deliberately raising an exception.

Beginner ~7 min read

Challenge 1

Catch the ValueError raised by int() and print "Invalid number.".

python Your answer
try:
    number = int("abc")
print("done")

Press Ctrl⌘Enter to check your answer

Challenge 2

Add an else block that prints the successful number.

python Your answer
try:
    number = int("42")
except ValueError:
    print("Invalid number.")

Press Ctrl⌘Enter to check your answer

Challenge 3

Add a finally block that prints "cleanup".

python Your answer
try:
    print("work")

Press Ctrl⌘Enter to check your answer

Challenge 4

Raise ValueError with the message "age must be non-negative" when age is below zero.

python Your answer
age = -1
if age < 0:

Press Ctrl⌘Enter to check your answer