您的位置:首页 > 编程语言 > Python开发

python学习笔记——第八章 异常

2014-05-08 21:44 731 查看
第八章 异常

1、捕捉异常:用try/except来实现

>>> try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print(int(x)/int(y))  #需要转换为整型
except ZeroDivisionError:
print("The second number can't be zero!")

Enter the first number: 10
Enter the second number: 0
The second number can't be zero!


捕捉异常并重新引发---用raise实现

>>> class MuffledCalculator:
muffled = False   #屏蔽开关的标志
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:  #若屏蔽开着,则捕捉异常并进行处理
print('Division by zero is illegal')
else:  #若屏蔽关着,则捕捉异常并重新引发
raise   #except捕捉到了异常,raise重新引发异常

>>>
>>> calculator = MuffledCalculator()
>>> calculator.calc('10/2')
5.0
>>> calculator.calc('10/0')   #屏蔽机制未打开,因为muffled = False
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
calculator.calc('10/0')  #屏蔽机制未打开,因为muffled = False
File "<pyshell#27>", line 5, in calc
return eval(expr)
File "<string>", line 1, in <module>
ZeroDivisionError: int division or modulo by zero
>>> calculator.muffled = True   #打开屏蔽机制
>>> calculator.calc('10/0')
Division by zero is illegal


多个except,捕捉多个不同类型的异常

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

Enter the first number: 2
Enter the second number: wsf
That wasn't a number. was it?


用一个块捕捉两个异常
>>> try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print(x/y)
except(ZeroDivisionError,TypeError,NameErrror):    #NameError找不到名字(变量)时引发
print('Your numbers were bogus....')


捕捉对象---想让程序继续运行,又想记录错误时应用
>>> try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print(x/y)
except (ZeroDivisionError, TypeError) as e:  #python3.0中的写法
print(e)

Enter the first number: 1
Enter the second number: 0
unsupported operand type(s) for /: 'str' and 'str'


捕捉所有的异常,except后不加东西

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

Enter the first number: "This" is "completely" illegal 123\
Enter the second number: 2
Something wrong happened...


#try/except/else情况:

>>> try:
print('A simple task')
except:
print('What? Something went wrong?')
else:
print('Ah...It went as planned.')

A simple task
Ah...It went as planned.

>>> while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = int(x)/int(y)
print('x/y is', value)
except:
print('Invalid input, Please try again.')
else:
break

Enter the first number: test
Enter the second number: 1
Invalid input, Please try again.
Enter the first number: 10
Enter the second number: 2
x/y is 5.0


# try/except Exception,e /else

>>> while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = int(x)/int(y)
print('x/y is', value)
except Exception as e:  #python 3.0的写法
print('Invalid input: ',e)
print('Please try again')
else:
break

Enter the first number: 1
Enter the second number: 0
Invalid input:  int division or modulo by zero
Please try again
Enter the first number: 'x'
Enter the second number: 'y'
Invalid input:  invalid literal for int() with base 10: "'x'"
Please try again
Enter the first number: quux
Enter the second number: 2
Invalid input:  invalid literal for int() with base 10: 'quux'
Please try again
Enter the first number: 10
Enter the second number: 2
x/y is 5.0


# try/finally

>>> try:
x = 1/0
finally:  #finally子句肯定会被执行
print('Cleaning up...')
del x

Cleaning up...
Traceback (most recent call last):
File "<pyshell#25>", line 2, in <module>
x = 1/0
ZeroDivisionError: int division or modulo by zero


# try/except/else/finally (可以用其中3个组合)

>>> try:
1/0
except NameError:
print("Unknown variable")
else:
print("That went well!")
finally:
print("Cleaning up.")


异常和函数

>>> def describePerson(Person):
print('Description of', person['name'])
print('Age:', Person['age'])
try:
print('Occupation:' + person['occupation'])  #打印职业时使用加号而不是逗号,否则字符串'Occupation:'在异常引发之前就会被输出
except KeyError:  #键不存在
pass

>>> person = {'name': 'Jack', 'age': 34}
>>> describePerson(person)
Description of Jack
Age: 34
#如果最后一句为print 'Occupation:', person['occupation']
#则出现
>>> describePerson(person)
Description of Sun
Age: 32
Occupation:
#所以要用加号连接,不用逗号,防止在异常发生前就被打印。


查看对象是否存在特定特性时,try/except很有用

>>> try:
obj.write
except AttributeError:
print('The Object is not writeable')
else:
print('The Object is writeable')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: