python基础学习代码之错误和异常

def func1():
try:
return float(‘abc’)
except valueerror,e:
print e
def func2():
try:
astr = ‘abc’
float(astr)
except valueerror:
astr = none
return astr
def func3():
try:
astr = ‘abc’
float(astr)
except valueerror:
astr = ‘count not convert non-number to float’
return astr
def safe_float(argment):
try:
retval = float(argment)
except valueerror:
retval = ‘count not convert non-number to float’
except typeerror:
retval = ‘object type cannot be convert to float’
return retval
def func4(argment):
try:
retval = float(argment)
except (valueerror,typeerror):
retval = ‘argment must be a number or numeric string’
return retval
def func5(argment):
try:
retval = float(argment)
except valueerror,e:
print e
print type(e)
print e.__class__
print e.__class__.__doc__
print e.__class__.__name__
def func6(argment):
try:
retval = float(argment)
except (valueerror,typeerror),e:
retval = str(e)
return retval
def main():
‘handles all the data processing’
log = open(‘e:\\cardlog.txt’,’w’)
try:
ccfile = open(‘e:\\cardlog.txt’,’r’)
txns = ccfile.readlines()
except ioerror,e:
log.write(‘no txns this month\n’)
log.close()
return
ccfile.close()
total = 0.00
log.write(‘account log:\n’)
for eachtxn in txns:
result = func6(eachtxn)
if isinstance(result,float):
total += result
log.write(‘data…processed\n’)
else:
log.write(‘ignored:%s’%result)
print ‘$%.2f newbalance’ % total
log.close()
#if __name__ == ‘__main__’:
# main()
def func7():
assert 1 == 0
def func8():
try:
assert 0 == 1,’one does not equal zero’
except assertionerror,e:
print ‘%s:%s’ % (e.__class__.__name__,e)
#assert
def func9(expr,args=none):
if __debug__ and not expr:
raise assertionerror,args
def func10():
try:
float(‘abc’)
except:
import sys
exect = sys.exc_info()
return exect
def func11():
try:
f = open(‘test.txt’)
except:
return none
else:
return f
def func12():
try:
raw_input(‘input data:’)
except (eoferror,keyboardinterrupt):
return none
import math,cmath
def safe_sqrt(data):
try:
ret = math.sqrt(data)
except valueerror:
ret = cmath.sqrt(data)
return ret
import sys
def func13():
try:
s = raw_input(‘enter something–>’)
except eoferror:
print ‘\nwhy did you do an eof on me?’
sys.exit(0)
except:
print ‘\nsome error/exception occurred.’
print ‘done’
func13()

以上就是python基础学习代码之错误和异常的内容,更多相关内容请关注php中文网(www.php1.cn)!

Posted in 未分类

发表评论