Index
What is try
and except
?
In Python, we use try
and except
to handle errors without crashing the program.
It’s like saying:
“Try this code, and if there’s an error, except (catch) it and do something else.”
Basic Syntax:
try:
# Code that may cause an error
risky_code()
except:
# Code to run if there is an error
handle_error()
Example 1: Handling Division by Zero
try:
result = 10 / 0
print("Result:", result)
except:
print("Oops! You can't divide by zero.")
Output:
Oops! You can't divide by zero.
Without try
, this would crash your program!
Example 2: Catching a Specific Error
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Please enter a valid number!")
What is else and finally?
The else
block lets you execute code when there is no error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
Example 3: Using else
and finally
try:
x = int(input("Enter a number: "))
print("You entered:", x)
except ValueError:
print("Invalid number!")
else:
print("Everything went fine!")
finally:
print("This will always run.")
Parts:
try
: Code that may cause an errorexcept
: Runs if there is an errorelse
: Runs if no errorfinally
: Runs no matter what
Why Use try-except
?
- Prevents your program from crashing
- Helps you handle user input errors
- Makes code more user-friendly