What is the function of the try block in Python exception handling?
a) To wrap code that might raise an exception
b) To catch and handle exceptions
c) To clean up resources after an exception
d) To raise an exception manually
Answer:
a) To wrap code that might raise an exception
Explanation:
The try
block in Python exception handling is used to wrap the code that might raise an exception. If an exception occurs within the try
block, the corresponding except
block is executed. If no exception occurs, the else
block (if present) is executed.
try:
# Code that might raise an exception
value = int(input("Enter a number: "))
except ValueError:
# Code to handle the exception
print("That's not a valid number!")
else:
# Code to execute if no exception occurs
print("You entered:", value)
In this example, the try
block contains code that attempts to convert user input to an integer. If the input is not a valid integer, a ValueError
is raised and handled by the except
block.
Using the try
block allows you to isolate potentially problematic code and handle exceptions in a controlled manner, improving the stability of your programs.