Try Out Things Safely!
Learn how to catch and handle user input errors safely.
We'll cover the following...
Our code can now make decisions, but what happens when something goes wrong?
In this lesson, we’ll learn how to use try and except to handle errors and keep our programs from crashing.
Break something (on purpose)
Try running this:
number = int(input("Enter a number: "))
print("Half of your number is", number / 2)Now run it again, but instead of entering a number, type something like hello.
We get an error: ValueError.
Why? This is because when the input isn’t something that can become a number (like "hello"), Python gets confused—it can’t turn that into an int, so it throws a ValueError and stops the program. This shows us: your code should never assume the user will follow instructions perfectly!
In Python, when something goes wrong during a program’s execution, it’s called an exception. ValueError is one type of exception.
try and except to the rescue
Let’s catch that error and show a friendly message instead:
try:
number = int(input("Enter a number: "))
print("Half of your number is", number / 2)
except:
print("Oops! That wasn’t a valid number.")Now, if something goes wrong, your program handles it gracefully instead of crashing.
How it works
try:tells Python to attempt some code.If something breaks, it jumps to the
except:block.We can catch errors and respond without crashing.
Want to be more specific?
We can catch specific errors like this:
try:
value = int(input("Type a number: "))
except ValueError:
print("That wasn’t a number!")This is great when we want to handle different errors in different ways.