python学习记录(八)

0910--https://www.cnblogs.com/fnng/archive/2013/04/28/3048356.html

Python异常

Python用异常对象(exception object)来表示异常情况。遇到错误后。会引发异常。如果异常对象未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行:

>>> 1/0
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero

raise语句

为了引发异常,可以使用一个类(Exception的子类)或者实例参数调用raise语句。下面的例子使用内建的Exception异常类:

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

系统自带的内建异常类:

自定义异常

尽管内建的异常已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和其他类一样,只是要确保从Exception类继承,不管是直接继承还是间接继承。像下面这样:

>>> class someCustomException(Exception):pass

捕捉异常

使用try/except来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the sencond number:'))
    z = x/y
    print(z)
except ZeroDivisionError:
    print('输入的数字不能为0!')

#输入
Enter the first number:1
Enter the sencond number:0
输入的数字不能为0!

假如,我们再调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。如何开启/关闭“屏蔽”机制?

class MuffledCalulator:
    muffled = False    #这里默认关闭屏蔽
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print ('Division by zero is illegal')
            else:
                raise

#运行程序:
>>> calculator = MuffledCalulator()
>>> calculator.calc('10/2')
5
>>> calculator.clac('10/0')

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    calculator.clac('10/0')
AttributeError: MuffledCalulator instance has no attribute 'clac'   #异常信息被输出了

>>> calculator.muffled = True   #现在打开屏蔽
>>> calculator.calc('10/0')
Divsion by zero is illagal 

多个except子句

如果运行输入两个数,求除法程序,输入非数字的内容,还会产生另外一个异常:

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the sencond number:'))
    z = x/y
    print(z)
except ZeroDivisionError:
    print('输入的数字不能为0!')
except ValueError:
    print('请输入数字')
#运行程序
Enter the first number: 10
Enter the second number: 'hello,word'
请输入数字!

一个块获取多个异常

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(x/y)
except (ZeroDivisionError,TypeError,NameError,ValueError):
    print("输入的内容有误,请输入非0数字!")
#运行程序
Enter the first number:1
Enter the second number:0
输入的内容有误,请输入非0数字!
#输入非数字
Enter the first number:a
输入的内容有误,请输入非0数字!

捕捉全部异常

就算以上处理了好几种异常,总有不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print (x/y)
except:
    print ('Sorry,Please enter again!')
#运行程序
Enter the first number:1
Enter the second number:djfjshfjkd
Sorry,Please enter again!

加入循环,若用户输入了错误信息,允许重新输入

while True:
    try:
        x = int(input('Enter the first number:'))
        y = int(input('Enter the second number:'))
        value = x/y
        print ('x/y is',value)
        break
    except:
        print ('输入的内容无效,请重新输入!')
#执行程序
Enter the first number:a
输入的内容无效,请重新输入!
Enter the first number:
输入的内容无效,请重新输入!
Enter the first number:1
Enter the second number:0
输入的内容无效,请重新输入!
Enter the first number:1
Enter the second number:3
x/y is 0.3333333333333333

猜你喜欢

转载自www.cnblogs.com/lu-test/p/9620836.html