Notes on Exception Handling in Python

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值