Catch multiple exceptions in Python

In Python, you can catch multiple exceptions in a single except block by using a tuple of exception types. Here's an example:

Code Example: Catching Multiple Exceptions

def process_data(data):
    try:
        # Simulate a potential error
        result = 10 / data  # Could raise ZeroDivisionError or TypeError
        print(f"Result: {result}")
    except (ZeroDivisionError, TypeError) as e:
        print(f"Error caught: {e.__class__.__name__} - {e}")
    except Exception as e:
        # Catch any other exceptions
        print(f"Unexpected error: {e.__class__.__name__} - {e}")
    else:
        # Execute if no exception occurs
        print("Processing completed successfully.")
    finally:
        # Execute whether or not an exception occurs
        print("Cleanup actions (if any).")

# Test cases
process_data(5)   # Valid input
process_data(0)   # ZeroDivisionError
process_data("a") # TypeError

Output

Result: 2.0
Processing completed successfully.
Cleanup actions (if any).

Error caught: ZeroDivisionError - division by zero
Cleanup actions (if any).

Error caught: TypeError - unsupported operand type(s) for /: 'int' and 'str'
Cleanup actions (if any).

Explanation

  1. Catch Multiple Exceptions:

    • The except (ZeroDivisionError, TypeError) as e line catches either of these exceptions and stores the exception instance in e.
    • You can access the exception type with e.__class__.__name__ and the message with str(e).
  2. Fallback except Block:

    • The final except Exception block catches any unexpected exceptions.
  3. else Block:

    • Runs if no exception occurs, useful for handling success cases.
  4. finally Block:

    • Executes regardless of whether an exception was raised, often used for cleanup operations (e.g., closing files or releasing resources).

Notes

  • Use multiple except blocks for more granular exception handling when needed.
  • Avoid overusing a blanket except Exception unless absolutely necessary, as it can hide programming errors.

댓글

이 블로그의 인기 게시물

Sparse encoder

To build a gRPC service with Gradle, Java, and Avro

Using venv in Python

how to delete doc of datastream in elasticsearch, 엘라스틱서치 데이터스트림 도규먼트 삭제하기

Typescript interface, 타입스크립트 인터페이스

Read a file in Java, 자바 파일 읽기

kubernetes cronjob logs

max_active_runs of Airflow

configure telnet server, 텔넷 서버 설정하기

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기