Junior
What is the purpose of the except construct in Python?
sobes.tech AI
Answer from AI
The except construction in Python is used for handling exceptions (errors) that occur during code execution. It is part of the try...except...finally block.
When an exception occurs in the try block, Python looks for a corresponding handler in the except block. If such a handler is found, the code inside this except block is executed. This prevents the program from crashing and allows for alternative actions.
- Basic usage: Handling any exception.
- Specifying exception type: Handling a specific type of exception.
- Handling multiple exceptions: Handling multiple types of exceptions in one or different
exceptblocks. - Accessing the exception object: Getting information about the exception.
Examples:
# Basic usage
try:
x = 1 / 0
except:
print("Division by zero error")
# Specifying exception type
try:
x = 1 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
# Handling multiple exceptions
try:
my_list = [1, 2]
print(my_list[3])
except IndexError:
print("Error: List index out of range.")
except ValueError:
print("Error: Invalid value.")
# Accessing the exception object
try:
my_list = [1, 2]
print(my_list[3])
except IndexError as e:
print(f"Error: {e}")