Python except statement
Created By: chatGPT
In Python, the except statement is used to catch and handle exceptions that may occur during the execution of a program. By using an except clause, you can prevent your program from crashing and handle the error gracefully. This is done within a try-except block. Here’s how you can use it:
try:
# Attempt to divide by zero
result = 10 / 0
except ZeroDivisionError:
# Handle the division by zero error
print("Cannot divide by zero!")
except Exception as e:
# Handle any other exception
print(f"An error occurred: {e}")
You can also use the else statement after your except block. The code inside the else block will run if the try block does not raise any exceptions. Here's an example:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
Additionally, the finally block can be used to execute code regardless of whether an exception was raised or not. This is often used for cleanup actions. Here’s how you can use it:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("This code runs no matter what.")
You can also catch multiple exceptions in a single except clause by using a tuple. This is useful when you want to handle different types of exceptions with the same response. Here's an example:
try:
result = int('not a number')
except (ValueError, TypeError) as e:
print(f"Caught an exception: {e}")