Python没有捕获异常



这是我的短代码:

def loadImage(img_file):
img = io.imread(img_file)           # RGB order
if img.shape[0] == 2: img = img[0]
if len(img.shape) == 2 : img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
if img.shape[2] == 4:   img = img[:,:,:3]
img = np.array(img)
return img
try:
image = loadImage(filename)
except Exception as e:
print("Error",e)

loadImage中的图像不存在。因此,错误发生在img = io.imread(img_file这一行。但Python没有抓住它

完整错误跟踪:

Traceback (most recent call last):
File "text_ocr.py", line 393, in processFiles
image = loadImage(filename)
File "text_ocr.py", line 129, in loadImage
img = io.imread(img_file)           # RGB order
File "C:Anaconda3libsite-packagesskimageio_io.py", line 48, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "C:Anaconda3libsite-packagesskimageiomanage_plugins.py", line 210, in call_plugin
return func(*args, **kwargs)
File "C:Anaconda3libsite-packagesskimageio_pluginsimageio_plugin.py", line 10, in imread
return np.asarray(imageio_imread(*args, **kwargs))
File "C:Anaconda3libsite-packagesimageiocorefunctions.py", line 264, in imread
reader = read(uri, format, "i", **kwargs)
File "C:Anaconda3libsite-packagesimageiocorefunctions.py", line 173, in get_reader
request = Request(uri, "r" + mode, **kwargs)
File "C:Anaconda3libsite-packagesimageiocorerequest.py", line 126, in __init__
self._parse_uri(uri)
File "C:Anaconda3libsite-packagesimageiocorerequest.py", line 278, in _parse_uri
raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'D:ProgramOCRtest_ocr3.png'

否。但我认为,除了Exception作为e之外,所有的错误都被抓住了吗?我错了吗?

所有内置的non-system-exiting异常都派生自Exception类。所有用户定义的异常也应该派生自此类。

但是,FileNotFoundError异常是OSError的子类。

试试这个:

try:
image = loadImage(filename)
except OSError as e:
print("Error",e)

一个小示例代码:

try:
image = open("i_donot_exist")
except OSError as e:
print("Exception Raised", e)

输出:

Exception Raised [Errno 2] No such file or directory: 'hehe'

有什么方法可以捕捉所有类型的错误吗?程序员定义的,内置定义的和所有类型的?

您需要放置多个except块来捕获所有类型的异常。参见以下示例:

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise

您还可以在一行中捕获多个异常。在Python文档中,except子句可以将多个异常命名为带括号的元组。有关详细信息,请参阅此链接。例如,

try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...

导入tracaback时,只需打印整个回溯错误,如下所示:

import traceback
try:
#code that might produce error
except:
traceback.print_exc()
pass

这实际上并没有捕捉到引发的异常——如果没有try-except块,错误也会显示在cli中。

最新更新