Snusifer
Snusifer

Reputation: 553

Raising more appropriate error after try statement in Python?

I am using openCV's cv2 for this, and i am not satisfied with the errors it produces. So I want to catch the error, and then raise a more appropriate error so the programmer gains better perspective of what went wrong:

try:
    cv2.imwrite(out_fn, img_arr, [jpg_q, 100, png_c, 9])
except:
    raise UnsupportedFileFormatError(out_fn)

However this just throws both exceptions:

Traceback (most recent call last):
  File "/Users/admin/Documents/Studie/IN3110/assignment4/Blur/blur/funcs/blur.py", line 25, in blur_image
    cv2.imwrite(out_fn, img_arr, [jpg_q, 100, png_c, 9])
cv2.error: OpenCV(4.1.1) /Users/travis/build/skvark/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:662: error: (-2:Unspecified error) could not find a writer for the specified extension in function 'imwrite_'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/admin/Documents/Studie/IN3110/assignment4/Blur/blur/funcs/blur.py", line 27, in blur_image
    raise UnsupportedFileFormatError(out_fn)
blur.errors.errors.UnsupportedFileFormatError: Unsupported file ending: "kyk.jp"

I want to do something like:

if cv2.error as e:
    e.ignoreError()
    throw new appropriateError()

Thats my way of illustrating something in a totally made-up pseudo programming language, but you get the point. How should I go about doing this? Thanks :))

Upvotes: 1

Views: 142

Answers (1)

Pedro Rodrigues
Pedro Rodrigues

Reputation: 2658

Couple things.

First. If you want to consume an exception, raise another from it.

try:
    ...
except ValueError as crap:
    raise AttributeError() from crap

Second. Do not hide exceptions blindly. Always be specific, and be sure the exception you're consuming only occurs when you expect it to.

Upvotes: 2

Related Questions