Error Handling with Try...Except in Python
The try...except
block is used for handling exceptions in Python. This allows your program to handle errors gracefully and continue execution.
Basic Try...Except Block:
Python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: Cannot divide by zero!
Handling Multiple Exceptions:
You can handle multiple exceptions by specifying different exception types in separate except
blocks:
Python
try:
x = int("abc")
except ValueError:
print("ValueError occurred")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: ValueError occurred
The Finally Block:
The finally
block allows you to execute code regardless of whether an exception occurred:
Python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This code runs no matter what.")
# Output:
# Cannot divide by zero!
# This code runs no matter what.
Raising Exceptions:
You can raise an exception manually using the raise
keyword:
Python
try:
x = -1
if x < 0:
raise ValueError("Negative value not allowed")
except ValueError as e:
print(e)
# Output: Negative value not allowed
Using try...except
allows you to manage errors in your programs and handle unexpected situations.
Import Links
Here are some useful import links for further reading: