Notes on Exception Handling in Python

本文介绍了Python中常见的异常类型,如IOError、ImportError等,并通过示例展示了如何使用try-except语句来处理这些异常。此外,还讲解了finally、else等关键字在异常处理中的应用。

Note: error and exception are the same in Python.

Common Exception

  • Exception Almost all the others are built off of it.
  • AttributeError Raised when an attribute reference or assignment fails.
  • IOError Raised when an I/O operation (e.g. a print statement, the built-in open() functio or a method of a file object) fails for an I/O-related reason, e.g. “file not found” or “disk full”.
  • ImportError Raised when an import statement fails to find the module definition or when a from ... import fails to find a name that is to be imported.
  • IndexError Raised when a sequence subscript is out of range.
  • KeyError Raise when a mapping (dictionary) key is not found in the set of existing keys.
  • KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or Del).
  • NameError Raised when a local/global name is not found.
  • OSError Raised when a function returns a system related error.
  • SyntaxError Raised when the parser encounters a syntax error.
  • TypeError Raised when an operation or function is applied to an object of inappropriate type. The associated value is string details about the type mismatch.
  • ValueError Raise when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
  • ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.

How to handle Exceptions

try:
    1/0
except ZeroDivisionError:
    print('You cannot divide by zero.')

# KeyError
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
exception KeyError:
    print('That key does not exist!')

# IndexError
my_list = [1, 2, 3]
try:
    my_list[5]
except IndexError:
    print('Index out of range.')

# A standard way to catch multiple exceptions
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except IndexError:
    #pass
except KeyError:
    #pass
except KeyError:
    #pass
except:
    #pass

Bare Excepts

# This is NOT recommended!
try:
    1/0
except:
    print('...')

The finally Statement

You can use the finally statement to clean up after yourself. You would also put the exit code at the end of the finally statement.

my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except KeyError:
    # pass
finally:
    # pass

try/except, or else

The else will only run if there are no errors raised.

my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
    value = my_dict['d']
except KeyError:
    # pass
else:
    print('NO error occurred!')
finally:
    print('....')

The only good usage of else statement is where you want ot execute a second piece of code that can also raise an error. Of course, if an error is raised in the else, it won’t get caught.

zsy@zsy-virtual-machine:~$ gnuradio-companion Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gnuradio/gr/__init__.py", line 37, in <module> from runtime_swig import * ModuleNotFoundError: No module named 'runtime_swig' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/gnuradio-companion", line 73, in check_gnuradio_import from gnuradio import gr File "/usr/lib/python2.7/dist-packages/gnuradio/gr/__init__.py", line 41, in <module> from runtime_swig import * ModuleNotFoundError: No module named 'runtime_swig' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/gnuradio-companion", line 99, in <module> check_gnuradio_import() File "/usr/local/bin/gnuradio-companion", line 75, in check_gnuradio_import die(err, GR_IMPORT_ERROR_MESSAGE) File "/usr/local/bin/gnuradio-companion", line 42, in die from gi.repository import Gtk File "/usr/lib/python2.7/dist-packages/gi/repository/__init__.py", line 25, in <module> from ..importer import DynamicImporter File "/usr/lib/python2.7/dist-packages/gi/importer.py", line 33, in <module> from .module import get_introspection_module File "/usr/lib/python2.7/dist-packages/gi/module.py", line 57, in <module> from .types import \ File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in <module> from . import _propertyhelper as propertyhelper File "/usr/lib/python2.7/dist-packages/gi/_propertyhelper.py", line 21, in <module> import traceback File "/usr/lib/python3.6/traceback.py", line 5, in <module> import linecache File "/usr/lib/python3.6/linecache.py", line 11, in <module> import tokenize File "/usr/lib/python3.6/tokenize.py", line 33, in <module> import re File "/usr/lib/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 62, in apport_excepthook if not enabled(): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled import re File "/usr/lib/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' Original exception was: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gnuradio/gr/__init__.py", line 37, in <module> from runtime_swig import * ModuleNotFoundError: No module named 'runtime_swig' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/gnuradio-companion", line 73, in check_gnuradio_import from gnuradio import gr File "/usr/lib/python2.7/dist-packages/gnuradio/gr/__init__.py", line 41, in <module> from runtime_swig import * ModuleNotFoundError: No module named 'runtime_swig' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/gnuradio-companion", line 99, in <module> check_gnuradio_import() File "/usr/local/bin/gnuradio-companion", line 75, in check_gnuradio_import die(err, GR_IMPORT_ERROR_MESSAGE) File "/usr/local/bin/gnuradio-companion", line 42, in die from gi.repository import Gtk File "/usr/lib/python2.7/dist-packages/gi/repository/__init__.py", line 25, in <module> from ..importer import DynamicImporter File "/usr/lib/python2.7/dist-packages/gi/importer.py", line 33, in <module> from .module import get_introspection_module File "/usr/lib/python2.7/dist-packages/gi/module.py", line 57, in <module> from .types import \ File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in <module> from . import _propertyhelper as propertyhelper File "/usr/lib/python2.7/dist-packages/gi/_propertyhelper.py", line 21, in <module> import traceback File "/usr/lib/python3.6/traceback.py", line 5, in <module> import linecache File "/usr/lib/python3.6/linecache.py", line 11, in <module> import tokenize File "/usr/lib/python3.6/tokenize.py", line 33, in <module> import re File "/usr/lib/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag'
06-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值