[파이썬] except 블록의 예외 타입 지정

Python’s except block allows us to catch and handle specific types of exceptions that may occur during the execution of our code. By specifying the exception type, we can create more robust error handling mechanisms and ensure that our program handles different types of exceptions in different ways.

The Syntax

The syntax to specify the exception type in the except block is as follows:

try:
    # code that may raise an exception
except ExceptionType:
    # exception handling code

Here, ExceptionType represents the specific type of exception that we want to catch. It can be any valid Python exception class or a tuple of exception classes.

Example

Let’s consider an example where we want to read a file and handle specific exceptions that may occur during the file processing.

try:
    file = open("my_file.txt", "r")
    content = file.read()
    file.close()
    # process the file content
except FileNotFoundError:
    print("File not found. Please check the file path.")
except PermissionError:
    print("Permission denied. Make sure you have the required permissions.")
except Exception as e:
    print("An error occurred:", str(e))

In the above example, we are attempting to open a file, read its content, and then process it. However, there are certain exceptions that can be raised, such as FileNotFoundError if the file does not exist or PermissionError if the user doesn’t have the required permissions.

By specifying these exception types in separate except blocks, we can handle each exception separately and provide more meaningful error messages to the user. In case any other unknown exception is raised, we catch it using the generic Exception type and print a generic error message along with the exception details.

Using Multiple Exception Types

We can also handle multiple exception types in a single except block by specifying a tuple of exception classes. This can be useful when we want to handle multiple similar exceptions in the same way.

try:
    # code that may raise multiple exception types
except (ExceptionType1, ExceptionType2):
    # exception handling code

Conclusion

By specifying the exception type in the except block, we can create more specific and targeted exception handling logic. This allows us to gracefully handle various exceptions that may occur in our code and provide appropriate feedback to the user. Remember to always handle exceptions properly to ensure the stability and reliability of your Python applications.