异常捕获

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. CentOS7 安装 hbase1.3.3

    1. 集群规划 ip地址 机器名 角色 192.168.1.101 palo101 hadoop namenode, hadoop datanode, yarn nodeManager, zookee ...

  2. TP微信扫码支付

    1.官网下载php扫码支付adk,放在项目引入第三方类库中 2.配置config中相关参数 注意:可能会遇到问题 微信支付错误问题的解决:curl出错,错误码:60 Fatal error: Unca ...

  3. websocket 群聊,单聊,加密,解密

    群聊 from flask import Flask, request, render_templatefrom geventwebsocket.handler import WebSocketHan ...

  4. 500 Internal Privoxy Error

    打开网站突然发现网站无法打开了,一脸懵逼,服务器重启也不行,明明能ping通,网上查的答案千奇百怪的 500 Internal Privoxy Error Privoxy encountered an ...

  5. python-ddt 数据驱动测试

    # @File : learn_ddt.py #-*- coding:utf-8 -*- #本次学习:ddt ---data drive test--数据驱动测试 #1.安装 pip install ...

  6. 检查Linux系统cpu--内存---磁盘的脚本

    花了一天写了三条命令分别检查cpu,内存,磁盘 [root@localhost ~]# cat cpu_mem_disk.sh #!/bin/sh # echo "1 检查cpu利用率--- ...

  7. 关于Access导入Oracle会产生双引号的问题

    把Access2007的数据导入到oracle 10g xe中,成功了,可是在写sql语句时必须加双引号 ,如select “name” from “Product”,貌似是因为access为了防止列 ...

  8. poi 导入Excel解析 2003 2007

    Workbook wb = WorkbookFactory.create(new FileInputStream(file)); Sheet sheet = wb.getSheetAt(0);// 第 ...

  9. SAP HANA数据库架构部署方法

    HANA作为内存数据库,在实现高性能访问的同时,必须也要有稳定的架构,今天我们就来看看企业部署SAP HANA时应该如何来设计数据库的架构. HANA数据库在安装时,有以下几种选择方法,为方便大家理解 ...

  10. .Net 上传文件和下载文件

    一.上传文件 1.普通的form表单提交 注意点: 请求方式必须为Post. form表单里必须设置enctype属性(enctype = "multipart/form-data" ...