Back to Python Mastery
IntermediateAdults
Error Handling with Try/Except
Sometimes, things go wrong in a program. A user might enter text when you expect a number, or you might try to divide by zero. If you don't handle these situations, your program will crash.
The
In this code:
- Python first tries to run the code in the
- If the user enters "abc", a
- If the user enters "0", a
- If no error occurs, the
This makes your programs much more robust and user-friendly.
The
try...except block lets you "try" a piece of code that might cause an error, and "catch" the error if it happens.try:number = int(input("Enter a number: "))result = 10 / numberprint(result)except ValueError:print("That wasn't a valid number!")except ZeroDivisionError:print("You can't divide by zero!")In this code:
- Python first tries to run the code in the
try block.- If the user enters "abc", a
ValueError occurs, and the code jumps to that except block.- If the user enters "0", a
ZeroDivisionError occurs, and it jumps to that block.- If no error occurs, the
except blocks are skipped.This makes your programs much more robust and user-friendly.
Safe Division Calculator
Create a function `safe_divide(a, b)` that returns the result of a / b. If b is zero, it should return the string "Error: Cannot divide by zero." instead of crashing.