In Python, you can catch specific exceptions using a try-except block. The try block contains the code that you want to execute, and the except block handles the exception if it occurs. Here’s an example:
try:
# code that might raise an exception
x = 10 / 0
except ZeroDivisionError:
# code to handle the ZeroDivisionError exception
print("Error: division by zero")
In this example, the try block contains the code that performs a division by zero, which raises a ZeroDivisionError exception. The except block catches the ZeroDivisionError exception and prints an error message.
You can also catch multiple exceptions in the same try-except block by specifying them as a tuple:
try:
# code that might raise an exception
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except (FileNotFoundError, ValueError) as e:
# code to handle the FileNotFoundError or ValueError exception
print("Error: {0}".format(e))
In this example, the try block contains the code that reads a line from a file and converts it to an integer. The except block catches either a FileNotFoundError or a ValueError exception and prints an error message that includes the exception information. Note that the exception object is assigned to the variable e, which can be used to access the exception information in the error message.
