天天看点

Python异常处理try...except的简单使用

1. try…except

有时候我们写程序的时候,会出现一些错误或异常,导致程序终止。使用try…except,这样程序就不会因为异常而中断。把可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,也可以处理一组圆括号中的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except。

a=10
b=0
try:
    c=a/b
    print (c)
except ZeroDivisionError as e:
    print (e)
print ("done")
           

运行:

division by zero
done
           

可以看出在有异常的情况下,程序依然执行完毕。

2. try …except…else

try …except…else语句,当没有异常发生时,else中的语句将会被执行。

a=10
b=0
try:
    c = b/ a
    print (c)
except (IOError ,ZeroDivisionError) as x:
    print (x)
else:
    print ("no error")
print ("done")
           

运行:

0.0
no error
done
           

3. raise 引发一个异常

raise是引发一个异常来检查某个条件是否成立。

inputValue=4.2
if type(inputValue)!=type(1):
    raise ValueError
else:
    print (inputValue)
           

运行:

...
    raise ValueError

ValueError
           

4. try …finally

无论异常是否发生,在程序结束前,finally中的语句都会被执行。

a=10
b=0
try:
    print (a/b)
finally:
    print ("always excute")

           

运行:

always excute
Traceback (most recent call last):
...
 print (a/b)

ZeroDivisionError: division by zero
           

可以看出finally最终执行,异常也照常报错。

5. try …except…finally

a=10
b=0
try:
    print (a/b)
except:
    print("error")
finally:
    print ("always excute")

           

结果:

error
always excute
           

6. 自定义一个异常类

自定义一个MyException类,继承Exception。

class MyException(Exception):
    
    def __init__(self,message):
        Exception.__init__(self)
        self.message=message  

a=9
if a<10:
    try:
        raise MyException("my excepition is raised ")
    except MyException as e:
        print (e.message)
           

结果:

my excepition is raised 
           

7. 把异常保存到一个日志文件中,来分析这些异常:

import traceback  
try:
    print ('here1:',5/2)
    print ('here2:',10/5)
    print ('here3:',10/0)
    
except Exception as e:
    f=open("log.txt",'a')  
    #traceback.print_exc(file=f)  # 打印输出到屏幕 
    traceback.print_exc(file=f)   # 输出到文件
    f.flush()  
    f.close()

           

结果:

here1: 2.5
here2: 2.0
           

会生成一个

log.txt

的文件。

8. 捕获异常的小方法

方法一:捕获所有异常

a=10
b=0
try:
    print (a/b)
except Exception as e:
    print(Exception,":",e)
finally:
    print ("always excute")
           

运行:

<class 'Exception'> : division by zero
always excute
           

方法二:采用traceback模块查看异常

import traceback   
try:
    print ('here1:',5/2)
    print ('here2:',10/5)
    print ('here3:',10/0)
    
except Exception as e:
    traceback.print_exc()
           

运行:

here1: 2.5
here2: 2.0
Traceback (most recent call last):
  File "/Users/lilong/Desktop/online_release/try_except_use.py", line 59, in <module>
    print ('here3:',10/0)
ZeroDivisionError: division by zero
           

方法三:采用sys模块回溯最后的异常

import sys   
try:
    print ('here1:',5/2)
    print ('here2:',10/5)
    print ('here3:',10/0)
    
except Exception as e:
    info=sys.exc_info()  
    print (info[0],":",info[1])
           

运行:

here1: 2.5
here2: 2.0
<class 'ZeroDivisionError'> : division by zero
           

注意:万能异常Exception

被检测的代码块抛出的异常有多种可能性,并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception,除非要对每一特殊异常进行特殊处理。

9. python所有的标准异常类:

异常名称 描述

BaseException:所有异常的基类

SystemExit: 解释器请求退出

KeyboardInterrupt: 用户中断执行(通常是输入^C)

Exception: 常规错误的基类

StopIteration: 迭代器没有更多的值

GeneratorExit: 生成器(generator)发生异常来通知退出

SystemExit Python :解释器请求退出

StandardError :所有的内建标准异常的基类

ArithmeticError :所有数值计算错误的基类

FloatingPointError :浮点计算错误

OverflowError :数值运算超出最大限制

ZeroDivisionError :除(或取模)零 (所有数据类型)

AssertionError: 断言语句失败

AttributeError: 对象没有这个属性

EOFError: 没有内建输入,到达EOF 标记

EnvironmentError :操作系统错误的基类

IOError: 输入/输出操作失败

OSError :操作系统错误

WindowsError :系统调用失败

ImportError :导入模块/对象失败

KeyboardInterrupt: 用户中断执行(通常是输入^C)

LookupError :无效数据查询的基类

IndexError: 序列中没有没有此索引(index)

KeyError: 映射中没有这个键

MemoryError: 内存溢出错误(对于Python 解释器不是致命的)

NameError :未声明/初始化对象 (没有属性)

UnboundLocalError :访问未初始化的本地变量

ReferenceError :弱引用(Weak reference)试图访问已经垃圾回收了的对象

RuntimeError: 一般的运行时错误

NotImplementedError: 尚未实现的方法

SyntaxError Python: 语法错误

IndentationError: 缩进错误

TabError Tab :和空格混用

SystemError: 一般的解释器系统错误

TypeError :对类型无效的操作

ValueError: 传入无效的参数

UnicodeError Unicode: 相关的错误

UnicodeDecodeError Unicode: 解码时的错误

UnicodeEncodeError Unicode :编码时错误

UnicodeTranslateError Unicode: 转换时错误

Warning: 警告的基类

DeprecationWarning :关于被弃用的特征的警告

FutureWarning :关于构造将来语义会有改变的警告

OverflowWarning :旧的关于自动提升为长整型(long)的警告

PendingDeprecationWarning :关于特性将会被废弃的警告

RuntimeWarning :可疑的运行时行为(runtime behavior)的警告

SyntaxWarning :可疑的语法的警告

UserWarning :用户代码生成的警告

参考:

https://www.cnblogs.com/Lival/p/6203111.html