Python 中的 try 语句后引发更合适的错误?
Raising more appropriate error after try statement in Python?
我正在为此使用 openCV 的 cv2,但我对它产生的错误不满意。所以我想捕获错误,然后引发更合适的错误,以便程序员更好地了解问题所在:
try:
cv2.imwrite(out_fn, img_arr, [jpg_q, 100, png_c, 9])
except:
raise UnsupportedFileFormatError(out_fn)
然而这只会抛出两个异常:
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"
我想做类似的事情:
if cv2.error as e:
e.ignoreError()
throw new appropriateError()
这就是我用一种完全虚构的伪编程语言来说明某些事情的方式,但你明白了。我应该怎么做呢?谢谢:))
两件事。
首先。如果你想消耗一个异常,从中引发另一个。
try:
...
except ValueError as crap:
raise AttributeError() from crap
其次。 不要 盲目隐藏异常。始终具体,并确保您使用的异常仅在您期望的时候发生。
我正在为此使用 openCV 的 cv2,但我对它产生的错误不满意。所以我想捕获错误,然后引发更合适的错误,以便程序员更好地了解问题所在:
try:
cv2.imwrite(out_fn, img_arr, [jpg_q, 100, png_c, 9])
except:
raise UnsupportedFileFormatError(out_fn)
然而这只会抛出两个异常:
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"
我想做类似的事情:
if cv2.error as e:
e.ignoreError()
throw new appropriateError()
这就是我用一种完全虚构的伪编程语言来说明某些事情的方式,但你明白了。我应该怎么做呢?谢谢:))
两件事。
首先。如果你想消耗一个异常,从中引发另一个。
try:
...
except ValueError as crap:
raise AttributeError() from crap
其次。 不要 盲目隐藏异常。始终具体,并确保您使用的异常仅在您期望的时候发生。