Sobes.tech
Intern
232

What is a try/except construct in Python?

Answer from AI

sobes.tech AI

The try/except construct is used to catch and handle exceptions (errors) that occur during code execution.

The try block contains code that might raise an exception. If an exception occurs, execution in the try block stops, and control is transferred to the corresponding except block. If no exception occurs, the except block is ignored.

The except block specifies the type of exception to catch and contains code to handle it. You can have multiple except blocks to handle different exception types, or use a single except without specifying a type to catch any exception.

Optionally, else and finally blocks can be used. The else block executes if no exceptions occur in the try block. The finally block always executes, regardless of whether an exception occurred or not, and is often used for resource cleanup.

// Basic example of try/except usage
try:
    result = 10 / 0 // Attempt to divide by zero, will raise ZeroDivisionError
    print(result) // This code will not execute due to the exception
except ZeroDivisionError:
    print("An error occurred: division by zero") // Catch and handle the exception
except Exception as e:
    print(f"An unexpected error occurred: {e}") // Catch any other exception
else:
    print("Division was successful") // Executes if no exceptions in try
finally:
    print("This block always executes") // Executes at the end, regardless of the outcome