Python Try-Except (Exception Handling) Tutorial
In Python, errors that occur during program execution are called exceptions. If exceptions are not handled, they stop the program. To prevent this, we use try-except blocks to handle errors gracefully.
1. Basic Try-Except Example
try:
x = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
✅ Explanation: If an error occurs inside try
, the except
block executes instead of crashing the program.
2. Handling Multiple Exceptions
try:
num = int(input("Enter a number: ")) # Input may not be an integer
result = 10 / num # Might cause division by zero
except ValueError:
print("Error: Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
✅ Explanation:
ValueError
occurs if input is not a number.ZeroDivisionError
occurs if input is0
.
3. Using a Generic Exception
try:
print(10 / 0)
except Exception as e:
print("Error:", e)
✅ Explanation: Exception as e
catches any error and prints its message.
4. Using Else and Finally
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Error: Invalid input!")
else:
print("No errors occurred.") # Runs if no error occurs
finally:
print("Execution completed.") # Always runs
✅ Explanation:
else
: Runs only if no exception occurs.finally
: Runs whether an error occurs or not (useful for cleanup).
5. Raising Exceptions Manually
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be 18 or older!")
✅ Explanation: raise
lets us trigger custom errors.
Conclusion
Using try-except
, we can prevent program crashes, improve user experience, and ensure smooth execution.
0 comments:
Post a Comment