第8章 异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010819416/article/details/82431790

8.1 异常是什么

8.2 让事情沿着你指定的轨道出错

8.2.1 raise语句

>>> raise Exception
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    raise Exception
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    raise Exception('hyperdrive overload')
Exception: hyperdrive overload
>>> 

8.2.2 自定义异常类

>>> class SomeCustomException(Exception):pass

>>> 

8.3 捕获异常

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")

8.3.1 不用提供参数

class MuffledCalculator:
    muffled = False

    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print('Divisiong by zero is illegal')
            else:
                raise
>>> calculator = MuffledCalculator()
>>> calculator.calc('10/2')
5.0
>>> calculator.calc('10/0')
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    calculator.calc('10/0')
  File "E:/python/python basic teach/8/raise.py", line 6, in calc
    return eval(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
>>> calculator.muffled = True
>>> calculator.calc('10/0')
Divisiong by zero is illegal
>>> 

8.3.2 多个except子句

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")
except TypeError:
    print("That was't a number,was is?")

8.3.3 一箭双雕

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(x / y)
except (ZeroDivisionError,TypeError,NameError,Exception):
    print("Your numbers were bogus")

8.3.5 一网打尽

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(x / y)
except:
    print("something wrong happened ...")

8.3.6 万事大吉时
没有出现异常时执行else子句


while True:
    try:
        x = int(input('Enter the first number:'))
        y = int(input('Enter the second number:'))
        print(x / y)
    except:
        print("something wrong happened ... again")
    else :
        break

8.3.7 最后
finally子句,在发生异常时执行清理工作。

x = None
try:
    x = 1/0
finally:
    print('cleaning up ...')
    del x

8.4 异常和函数

8.5 异常之禅

8.6 不那么异常的情况
只想发出警告。

>>> from warnings import warn
>>> warn("warning ...")

Warning (from warnings module):
  File "E:/python/python basic teach/8/finally.py", line 1
    x = None
UserWarning: warning ...
>>> 

8.7 小结

猜你喜欢

转载自blog.csdn.net/u010819416/article/details/82431790