Python基础--异常


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语句都会执行。

评论关闭