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

Python基础--异常

2016-03-19 22:11 477 查看
Google C++ Style中禁止使用异常。

Python中也有异常,就简单分享一下。

1/0就会产生异常。

按自己的方式出错

raise语句

>>>raise Exception
Traceback (most recent all last):


自定义异常类

class SomeCustomException(Exception):pass


捕捉异常 try/except

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


多个except

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


一个excep捕捉多个异常

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


try/except/else

try:
print' '
except:
print' '
else:
print' '


finally语句

不管是否引发了异常,finall语句都会执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: