Yes, it is possible to nest try-except blocks in Python. Nesting try-except blocks allows you to handle exceptions at different levels of your code and perform specific actions based on the type of exception that occurs.
Here's an example of nested try-except blocks:
try:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Error: You must enter a valid number.")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
else:
print("The result is:", result)
except:
print("An unexpected error occurred.")
In this example, there are two try-except blocks. The inner try block prompts the user to enter two numbers, divides the first number by the second number, and assigns the result to the result variable. If the second number is zero, a ZeroDivisionError will be raised, and the except block inside the inner try block will be executed.
If a non-numeric value is entered, a ValueError will be raised, and the except block inside the inner try block will be executed. If no exceptions are raised, the code in the else block of the inner try block will be executed.
If an exception occurs inside the inner try block, the outer try block will catch the exception and print a generic error message.
Overall, nesting try-except blocks is a useful technique in Python that allows you to handle exceptions at different levels of your code and perform specific actions based on the type of exception that occurs.