ラーフル・シャルマ:
これは私の短いコードです。
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:\Anaconda3\lib\site-packages\skimage\io\_io.py", line 48, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "C:\Anaconda3\lib\site-packages\skimage\io\manage_plugins.py", line 210, in call_plugin
return func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\skimage\io\_plugins\imageio_plugin.py", line 10, in imread
return np.asarray(imageio_imread(*args, **kwargs))
File "C:\Anaconda3\lib\site-packages\imageio\core\functions.py", line 264, in imread
reader = read(uri, format, "i", **kwargs)
File "C:\Anaconda3\lib\site-packages\imageio\core\functions.py", line 173, in get_reader
request = Request(uri, "r" + mode, **kwargs)
File "C:\Anaconda3\lib\site-packages\imageio\core\request.py", line 126, in __init__
self._parse_uri(uri)
File "C:\Anaconda3\lib\site-packages\imageio\core\request.py", line 278, in _parse_uri
raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'D:\Program\OCR\test_ocr\3.png'
Abhiaror:
いいえ。しかし、私はすべてのエラーをキャッチし、電子などの例外を除いてと思いますか?私が間違っている?
すべてのビルトインは、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
また、1つの行に複数の例外をキャッチすることができます。Pythonドキュメント、except節アンは、括弧内のタプルとして複数の例外を指定することができます。参照してください。この詳細については、リンクを。例えば、
try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...