Try and Except
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Try and Except
Exception Handling
Definition: The try...except block is used in Python to handle errors and exceptions. It allows a program to catch unexpected errors during execution and respond gracefully instead of crashing completely.
Why: Real-world programs interact with unpredictable inputs, missing files, or network drops. Teaching exception handling early ensures you build resilient applications that can report an issue to the user and keep running safely rather than abruptly shutting down.
How It Works
- The
tryBlock: You place the code that *might* cause an error inside this block. Python will attempt to run it normally. - The
exceptBlock: If an error occurs inside the try block, Python immediately stops execution there and jumps straight to this block to run the recovery code.
Example
try:
num = int(input("Enter a number: "))
print(num)
except ValueError:
print("Please enter a valid number")
Explanation
- The Code Inside
try: Theinput()function reads text from the user, andint()tries to convert that text into a whole number. - The Potential Error: If a user types
"hello"instead of a number, theint()function cannot convert it and throws aValueError. - The Catch: Because we specified
except ValueError:, Python catches that specific error and prints a helpful message rather than showing a confusing technical error screen to the user.
Expanding the Control Flow
You can make exception handling more robust by adding optional else and finally blocks:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("Error: The file does not exist.")
else:
print("File read successfully!") # Runs ONLY if the try block succeeds without errors
finally:
print("Execution complete.") # ALWAYS runs, no matter what happens above
Key Notes
- Catching Specific Errors: It is best practice to catch specific exceptions (like
ValueErrororZeroDivisionError) rather than using a bareexcept:block, which could accidentally hide unrelated bugs in your code. - The
asKeyword: You can capture the error message itself into a variable to log it or print it (e.g.,except ValueError as error:). - If no error occurs inside the
tryblock, theexceptblock is completely skipped.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute