免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1558 | 回复: 0
打印 上一主题 下一主题

《python 从入门到精通》 §8 例外 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-18 10:44 |只看该作者 |倒序浏览


  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}
§8    例外
§8.1 什么是例外
>>> 1/0
Traceback (most recent call last):
File "", line 1, in
?
ZeroDivisionError: integer division or
modulo by zero

§8.2 出现例外的方法
>>> raise Exception('hyperdrive
overload')
Traceback (most recent call last):
File "", line 1, in
?
Exception: hyperdrive overload

查看例外种类:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError',
'AttributeError', ...]

>>> raise ArithmeticError
Traceback (most recent call last):
File "", line 1, in
?
ArithmeticError
重要的例外种类见教材186页

自定义例外类:
class SomeCustomException(Exception): pass
§8.3 获取例外
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y

Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
File "exceptions.py", line 3, in
?
print x/y
ZeroDivisionError: integer division or
modulo by zero

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!"

也可以用if语句来判断,不过如果有多个分母,一个try就可以搞定了。

在没有交互式的情况,使用print更好:
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

>>> calculator =
MuffledCalculator()
>>> calculator.calc('10/2')
5
>>> calculator.calc('10/0') # No
muffling
Traceback (most recent call last):
File "", line 1, in
?
File "MuffledCalculator.py", line
6, in calc
return eval(expr)
File "", line 0, in
?
ZeroDivisionError: integer division or
modulo by zero
>>> calculator.muffled = True
>>> calculator.calc('10/0')
Division by zero is illegal

同时捕捉多个错误:
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?"

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

用log记录例外:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError, TypeError), e:
print e

捕捉所有错误:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except:
print 'Something wrong happened...'
       一般不建议使用,可能会隐藏错误。

try:
print 'A simple task'
except:
print 'What? Something went wrong?'
else:
print 'Ah... It went as planned.'
If you run this, you get the following
output

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

               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2030509.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP