What is an exception?
When something goes wrong at runtime (e.g., converting text to a number), Python raises an exception. If it’s not handled, the program stops and prints a traceback. You can catch and respond to these problems using try/except.
General exception handling
Wrap risky code in try. If an error occurs, control jumps to except. Use else to run code only if there was no exception.
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except:
print("Error: Please enter a valid number.")
else:
print("Thank you for providing your age.")
Catching specific exceptions
Catch particular error types to give clearer messages. For example, ValueError means the input had the wrong type, and ZeroDivisionError means division by zero.
try:
num = float(input("Enter a number: "))
result = num / 999
print("The result is", result)
except ValueError:
print("Error: That was not a valid number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Using else and finally
else runs only when no exceptions occur. finally always runs (success or failure)—useful for cleanup.
try:
n = int(input("Enter an integer: "))
print("Double is", n * 2)
except ValueError:
print("Please enter a whole number.")
else:
print("Nice! That worked.")
finally:
print("Finished trying to process your input.")
Practice Task 1: Age input with error handling
Prompt for age with int(), handle bad input.
try:
user_age = int(input("Please enter your age: "))
print("Your age is", user_age)
except ValueError:
print("Invalid input! Please enter a numerical value for your age.")
Practice Task 2: Division with specific exceptions
Ask for a number, divide it by 999, and handle invalid input (and zero, if it ever occurs).
try:
value = float(input("Enter a number to divide by 999: "))
quotient = value / 999
print("The quotient is:", quotient)
except ValueError:
print("Invalid input! Please provide a numeric value.")
except ZeroDivisionError:
print("Division by zero error! Please check your input.")
- Catch specific exceptions when you can; use a general
exceptas a last resort. - Use
elsefor code that should only run when no error occurs. - Use
finallyfor cleanup (closing files, releasing resources).