Skip to content

Instantly share code, notes, and snippets.

@wcDogg
Last active January 21, 2023 05:01
Show Gist options
  • Save wcDogg/6a50ae832e750ba074ab348eb45eab98 to your computer and use it in GitHub Desktop.
Save wcDogg/6a50ae832e750ba074ab348eb45eab98 to your computer and use it in GitHub Desktop.

Python: Catch Warnings with Try Except

Today I needed to handle a Pillow warning. Many posts demonstrate how to treat all warnings as exceptions so they can be caught with try and exept. I quickly discovered that catching all warnings can be problematic. Here's how to catch specific warnings:

import warnings
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)

def process_images():
  try:
    some_process()

  except Image.DecompressionBombWarning as e:
    print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment