我为此使用了 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
第二。 不要盲目隐藏异常。始终要具体,并确保您所使用的异常仅在您期望的时候发生。
关于python - 在Python中的try语句后引发更合适的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58173048/