Python is not catching exception

rahul sharma :

This is my short code:

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)

The image inside loadImage does not exist. So the error happens at this line img = io.imread(img_file. But Python is not catching it

Full error trace:

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'
abhiarora :

No. But I think except Exception as e, catch all errors? Am I wrong?

All built-in, non-system-exiting exceptions are derived from Exception class. All user-defined exceptions should also be derived from this class.

However, The FileNotFoundError exception is subclasses of OSError.

Try this:

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

A small example code:

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

Outputs:

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

Any way to catch all types of errors? Programmer defined, built-in defined and all types on earth?

You need to put multiple except blocks to catch all type of exception. See an example below:

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

You can also catch multiple exceptions in one line. From Python Documentation, An except clause may name multiple exceptions as a parenthesized tuple. See this link for more information. For example,

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17916&siteId=1