Exception Handling
Exception Handling is a reusable Python snippet. Handle errors gracefully using try/except/else/finally blocks. The full implementation: # Basic try/except try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") # Multiple exception types try: x = int(input("Enter a number: ")) result = 100 / x except ValueError: print("Invalid number!") except ZeroDivisionError: print("Can't divide by zero!") else: print(f"Result: {result}") # Runs if no exception finally: print("This always runs") # Cleanup # Custom exception class CustomError(Exception): pass raise CustomError("Something went wrong") It belongs to the Statements & Keywords area of the standard library. This snippet uses only the Python standard library with no third-party dependencies, so it runs on any modern Python 3 interpreter. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.