Python异常初识

本文作为自己的学习笔记,已尽力详细描述和准确,难免会出现错误,所以这是一个beta版本。

首先什么是异常,

在python或者程序中,由于语法,逻辑或者系统的错误而导致程序出现错误无法执行,而这个错误就是异常。

异常分为两个阶段:

1,引起异常发生的错误

2,检测(也就是采取措施)阶段

python中的异常分为很多种,常见的有如下异常:

1,NameError

>>> foo

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    foo
NameError: name 'foo' is not defined

2,SyntaxError: Python解释器语法错误

>>> for
SyntaxError: invalid syntax

3,KeyError:请求一个不存在的字典关键字

4,IOError:输入/输出错误

等等。所有错误的分类如下:

-BaseException
|-KeyboardInterrput
|-SystemExit
|-Exception(除了以上连个异常,所有的异常分类到这里)
	|-(all other current built-in exceptions)

在python中如何捕获异常

try:
    try_suite
except Exception[,reasion]:
    except_suite
注意在 except 中的代码块,在异常没有发生时,这些代码块是永远不会到达。

例:

try:
	f = open('blah','r')
except IOError, e:
	print 'could not open file:',e

同样的情况下,try后面可以跟多个except 来处理不同的异常,当然也可以跟一个来处理同类的异常,语法分别如下:

try:
	try_suite
except Exception [,reason1]:
	suite_for_exception_Exception1
except Exception [,reason2]:
	suite_for_exception_Exception2
		:

处理多个异常的except 语句:

try:
	try_suite
except (Exception1,Exception2) [,reason1]:
	suite_for_exception_Exception1_and_Exception2

例:

import sys
try:
    s = raw_input('Enter something -->')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit()
except:
    print '\nSome error/exception occurred.'
print 'Done'

例:

def safe_float(obj):
	try:
		retval= float(obj)
	except (ValueError,TrypeError):
		retval ='argument must be a number or numeric string'
	return retval

另外一个用户是捕获所有的异常,但是我建议这样子做

try:
	:
except Exception,e:
	suit_Exception

else 子句:

在try 范围中没有异常被检测到时,执行else子句。

例:

import 2rd_party_module
log = open('logfile.txt','w')
try:
	3rd_party_module.function()
except:
	log.write("*** caught exception in module\n")
else:
	log.write("*** no exception caught\n")

finally 子句

try:finally不是用来捕获异常,而是来替代的

try:
	try_suite
finally:
	finallyu_suite #无论如何都要执行

try-except-else-finally: 

try:
	try_suite
except Exception1:
	suite_for_Exception1
except (Exception2,Exception3,Exception4):
	suite_for_Exception_2_3_and4
except Exception5,Argument5:
	suite_for_Exception_plus_argument
except:
	suite_for_all_other_exceptions
else:
	no_exceptions_detected_suite
finally:
	always_execute_suite

触发异常

raise

例:

#/usr/bin/env python
try:
    assert 1==0,'one does not equal zero siily!'
except AssertionError,arges:
    print '%s: %s' %(arges.__class__.__name__,arges)














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值