python中的错误处理

yipeiwu_com6年前Python基础

用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错:

def foo():
  r = some_function()
  if r==(-1):
    return (-1)
  # do something
  return r

def bar():
  r = foo()
  if r==(-1):
    print 'Error'
  else:
    pass

但是Go就是这么干的,哈哈!

python 中还是用try … except….finally这种方式来处理的。

try:
  print 'try...'
  r = 10 / 0
  print 'result:', r
except ZeroDivisionError, e:
  print 'except:', e
finally:
  print 'finally...'
print 'END'

相关文章

Python 中开发pattern的string模板(template) 实例详解

定制pattern的string模板(template) 详解 string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式....

【python】matplotlib动态显示详解

【python】matplotlib动态显示详解

1.matplotlib动态绘图 python在绘图的时候,需要开启 interactive mode。核心代码如下: plt.ion(); #开启interactive mode...

python cookielib 登录人人网的实现代码

先上脚本吧,等下来讲下知识点: 复制代码 代码如下: #!/usr/bin/env python #encoding=utf-8 import sys import re import...

Python 、Pycharm、Anaconda三者的区别与联系、安装过程及注意事项

Python 、Pycharm、Anaconda三者的区别与联系、安装过程及注意事项

1、致欢迎词 我将详细讲述在学Python初期的各种手忙脚乱的问题的解决,通过这些步骤的操作,让你的注意力集中在Python的语法上以及后面利用Python所解决的项目问题上。而我自己作...

简单掌握Python的Collections模块中counter结构的用法

counter 是一种特殊的字典,主要方便用来计数,key 是要计数的 item,value 保存的是个数。 from collections import Counter >...