The Try and Except Block
Part of the Logic & Flow section of Coddy's Python journey — lesson 64 of 78.
The try-except block in Python allows you to handle exceptions and prevent your program from crashing. Code that might raise an exception is placed inside the try block, and the except block handles the error if it occurs.
Here’s the basic structure:
try:
# Code that might cause an exception
risky_code()
except ExceptionType:
# Code to handle the exception
handle_error()Example:
try:
num = int("abc") # This raises a ValueError
except ValueError:
print("Invalid input! Please enter a number.")Output:
Invalid input! Please enter a number.In this example, instead of crashing, the program catches the ValueError and prints a friendly message. Use try-except to handle specific exceptions and keep your program running smoothly.
Challenge
EasyWrite a program that prompts the user to enter a number. Use a try-except block to handle cases where the input is not a valid integer.
- If the user enters a valid integer, print
"You entered: <number>". - If the user enters an invalid value (e.g., a string or special character), catch the exception and print
"Invalid input! Please enter a valid number.".
Cheat sheet
The try-except block handles exceptions and prevents program crashes. Place risky code in the try block and error handling in the except block:
try:
# Code that might cause an exception
risky_code()
except ExceptionType:
# Code to handle the exception
handle_error()Example with ValueError:
try:
num = int("abc") # This raises a ValueError
except ValueError:
print("Invalid input! Please enter a number.")Try it yourself
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?The Try and Except BlockHandling Multiple ExceptionsRecap - Shopping Cart Errors