异常捕获

try

基本概念

我们使用try except来捕获异常,python的try except有几个特点:

  • 不管函数内部嵌套几层,只要在try的范围内就可以被捕获。这句话的意思是一个函数被try语句包裹,这个函数中调用了另一个函数。如果被调用函数中发生了异常,那么在外层的函数中是可以被捕获到的;

特点

  • try except finally的执行逻辑是

    ** 正常逻辑是try -》finally

    ** 错误逻辑是try -》except -》finally

except

基本概念

except中有各种类型的异常,其中基类是BaseException。具体可以参考:https://docs.python.org/3/library/exceptions.html#exception-hierarchy

BaseException

+-- SystemExit

+-- KeyboardInterrupt

+-- GeneratorExit

+-- Exception

+-- StopIteration

+-- StopAsyncIteration

+-- ArithmeticError

| +-- FloatingPointError

| +-- OverflowError

| +-- ZeroDivisionError

+-- AssertionError

+-- AttributeError

+-- BufferError

+-- EOFError

+-- ImportError

+-- ModuleNotFoundError

+-- LookupError

| +-- IndexError

| +-- KeyError

+-- MemoryError

+-- NameError

| +-- UnboundLocalError

+-- OSError

| +-- BlockingIOError

| +-- ChildProcessError

| +-- ConnectionError

| | +-- BrokenPipeError

| | +-- ConnectionAbortedError

| | +-- ConnectionRefusedError

| | +-- ConnectionResetError

| +-- FileExistsError

| +-- FileNotFoundError

| +-- InterruptedError

| +-- IsADirectoryError

| +-- NotADirectoryError

| +-- PermissionError

| +-- ProcessLookupError

| +-- TimeoutError

+-- ReferenceError

+-- RuntimeError

| +-- NotImplementedError

| +-- RecursionError

+-- SyntaxError

| +-- IndentationError

| +-- TabError

+-- SystemError

+-- TypeError

+-- ValueError

| +-- UnicodeError

| +-- UnicodeDecodeError

| +-- UnicodeEncodeError

| +-- UnicodeTranslateError

+-- Warning

+-- DeprecationWarning

+-- PendingDeprecationWarning

+-- RuntimeWarning

+-- SyntaxWarning

+-- UserWarning

+-- FutureWarning

+-- ImportWarning

+-- UnicodeWarning

+-- BytesWarning

+-- ResourceWarning


特点

异常的特点有:

  • 父类的异常捕获到,其后如果有子类也捕获异常,那么子类的异常捕获是失效的
  • 堆栈是按照顺序抛出异常的,在出错的时候可以顺着异常堆栈排查
'a demo class of except'

__author__ = 'liyue'

class  MyExceptionTest:
#通过try except finally处理异常
def fun1(self):
try:
print('begin to calc 10/0:')
i = 10/0
print('calc successful')
except ZeroDivisionError as e:
print('ValueError:', e)
finally:
print('calc finally') #父类捕获异常,子类无效
def fun2(self):
try:
print('begin to calc 10/0:')
i = 10/0
print('calc successful') except BaseException as be:
print('This is BaseException :%s' % be)
except ZeroDivisionError as e:
print('This is ValueError:%s' % e) finally:
print('calc finally') if __name__ == '__main__':
m = MyExceptionTest()
m.fun1()
m.fun2()

记录异常

  • 记录异常可以用python內建logging模块,通过配置可以把logging信息记录到日志中。
  • 如果有logging,异常打印后,logging记录完后会继续执行完后续代码
#logging记录异常
def fun3(self):
try:
print('fun3:')
print('begin to calc 10/0:')
i = 10/0
print('calc successful')
except ZeroDivisionError as e:
logging.exception(e)
finally:
print('3 calc finally')

抛出错误

我们使用raise来抛出错误,特点有:

  • 可以自定义抛出,但是前提是没有內建异常,或者实际需要
  • 可以在except中把适当的exception转换为另一个种抛出,前提是这种转换合理的
'a demo class of except'
__author__ = 'liyue' import logging class MyError(ValueError):
pass class MyExceptionTest:
#通过try except finally处理异常
def fun1(self, n):
if n==0:
raise MyError('This is my error')
return 10/n if __name__ == '__main__':
m = MyExceptionTest()
m.fun1(0)

调试

print()

print()方法是最常见的调试,在调试中直接打印信息,但是需要每次编码,且最终使用中不方便

assert()

断言也是一种通用的调试方法,但是不友好。使用也不方便

pdb

调试需要配置环境和下载pdb,开发阶段配置好可用,但是不具有通用性。

logging

日志是最有效最通用的方式,既可以调试也可以在非调试环境下使用。

日志的配置有多种形式,api里有说明。这里取了最常用的。多模块可配置打印:

'a demo class of except'
__author__ = 'liyue' import logging
#logging.basicConfig(filename='d:\example.log',level=logging.DEBUG) #简单的打印
#常见的通用打印,包含了输出路径、输出名称、级别、时间和信息
logging.basicConfig(filename='d:\example.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') class MyDebug(object): def assertTest(self, n):
if n == 0:
assert() def logTest(self, msg):
#这两句是单模块打印时候使用,如果设计中不需要模块信息输出也可以直接这样使用
#logging.info(msg)
#logging.debug(msg) #更为通用的多模块打印,是常见的打印模式
logger = logging.getLogger('ly demo')
logger.warning(msg) if __name__ == '__main__':
m = MyDebug()
#m.assertTest(0)
m.logTest('This is a test log info')
m.logTest('print some infomation')

Python异常和调试.md的更多相关文章

  1. python 异常

    引用一段来自菜鸟教程的文章:http://www.runoob.com/python/python-exceptions.html Python 异常处理 python提供了两个非常重要的功能来处理p ...

  2. 小学生绞尽脑汁也学不会的python(异常,约束,MD5加密,日志处理)

    小学生绞尽脑汁也学不会的python(异常,约束,MD5加密,日志处理) 异常处理(处理) 1.产生异常.raise 异常类(),抛出异常2. 处理异常: try: xxxxx # 尝试执行的代码. ...

  3. 【AMAD】stackprint -- 为Python加入利于调试的traceback信息

    简介 动机 作用 用法 热度分析 源码分析 个人评分 简介 为Python加入利于调试的traceback信息.  动机 Python抛出异常时,会显示一些traceback信息.但是,一些时候这些 ...

  4. [转] python程序的调试方法

    qi09 原文 python程序的调试方法 本文讨论在没有方便的IDE工具可用的情况下,使用pdb调试python程序 源码例子 例如,有模拟税收计算的程序: #!/usr/bin/python de ...

  5. [置顶] 如何在Python IDLE中调试Python代码?

    好久没有用Python了,居然忘记了怎么在Python IDLE中调试Python代码.百度了一下,然后还是写下来吧,以免以后又忘记了. 1. Set break point in the sourc ...

  6. #21 Python异常

    前言 运行程序时经常遇到各种错误,例如:ImportError(导入模块错误).IndexError(索引错误).NameError(变量错误).SyntaxError(语法错误).Indentati ...

  7. Python异常和异常处理

    Python异常和异常处理2017年12月20日 22:17:08 Megustas_JJC 阅读数:114 标签: python 异常处理 更多 个人分类: Python 版权声明:本文为博主原创文 ...

  8. python——异常except语句用法与引发异常

    except: #捕获所有异常 except: <异常名>: #捕获指定异常 except:<异常名1,异常名2):捕获异常1或者异常2 except:<异常名>,< ...

  9. 笔记-python异常信息输出

    笔记-python异常信息输出 1.      异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...

随机推荐

  1. XML与 实体的相互转化

    using System; using System.Linq; using System.Xml; using System.Reflection; using System.Data; using ...

  2. SSH2 No Session found for current thread原因

    Hibernate4 与 spring3 集成之后, 如果在取得session 的地方使用了getCurrentSession, 可能会报一个错:“No Session found for curre ...

  3. 《Linux 性能及调优指南》1.5 网络子系统

    翻译:飞哥 (http://hi.baidu.com/imlidapeng) 版权所有,尊重他人劳动成果,转载时请注明作者和原始出处及本声明. 原文名称:<Linux Performance a ...

  4. mocha、should、supertest释义

    解释参考地址: https://itbilu.com/nodejs/npm/VyrFOe51-.html Mocha模块 Mocha是一个简单.可扩展的用于Node.js和JavaScript的单元测 ...

  5. 14.json文件读取

    json文件读取 1.#读取json import json str='''[ { "name":"Tom", "gender":" ...

  6. 笔记:js疑难复习

    apply 和 call的区别 call 和 apply 的区别只在于这两个函数接受的参数形式不同 var Person = function(name,age){ this.name = name; ...

  7. 37.如何把握好 transition 和 animation 的时序,创作描边按钮特效

    原文地址:https://segmentfault.com/a/1190000015089396 拓展地址:https://scrimba.com/c/cWqNNnC2 HTML code: < ...

  8. 《算法》第五章部分程序 part 8

    ▶ 书中第五章部分程序,包括在加上自己补充的代码,适用于基因序列的 2-Bit 压缩算法,行程长压缩算法,Huffman 压缩算法,LZW 压缩算法 ● 适用于基因序列的 2-Bit 压缩算法 pac ...

  9. leetcode984

    public class Solution { private string M1(int A, int B) { StringBuilder sb = new StringBuilder(); ; ...

  10. 01-css的引入方式和常用选择器

    一.css介绍 现在的互联网前端分三层: HTML:超文本标记语言.从语义的角度描述页面结构. CSS:层叠样式表.从审美的角度负责页面样式. JS:JavaScript .从交互的角度描述页面行为 ...