为了账号安全,请及时绑定邮箱和手机立即绑定

python异常处理

标签:
Python

程序的错误通常分为,语法错误,运行错误和逻辑错误

一个最常见的错误

>>> print(a)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

python的异常

异常类名 说明
Exception 所有异常的基类
AttributeError 访问未知对象的属性
IOError io异常
IndexError 不存在的索引
NameError 不存在的变量名

异常处理的语句

try:
    语句块
except:
    异常处理的语句

python中,异常处理是通过try--except语句实现的,try检测语句块中的错误,except语句是捕获异常,并进行处理。如果不希望程序在异常发生而结束,只需在try捕获。

执行try语句块,如果正常则结束到try--ecxept语句下一条语句,否则执行exception的异常处理语句

def calcu():
    a,b=eval(input())
    try:
        end=a/b
        print('end=',end)
    except:
        print('error')

结果

>>> calcu()
1,2
end= 0.5
>>> calcu()
1,0
error

分类异常处理


def main():
    a,b=eval(input())
    try:
        s=a/b
        print('s=',s)
    except TypeError :
        print('数据类型异常,')
    except ZeroDivisionError as e:
        print('除数为0,',e)
    except:
        print(' 发生exception')
    else:
        print('正常结束')

结果是

>>> main()
1,'1'
数据类型异常,
>>> main()
1,0
除数为0, division by zero
>>> main()
2,3
s= 0.6666666666666666
正常结束

try--finally语句。
finally语句是指无论是否发生,都执行相应的语句块。

import os
def main():
    try:
        f1=open('C:\\HelloWorld.txt','r+')
        f2=open('c:\\test.txt','w+')
        f3=f1.read()
        f1.seek(0)
        print(f3)
        print('----------')
        for c in f1:
            f2.write(c)
    except:
        print(' has except')
    finally:
        print('close file')
        f2.flush()
        #f2.seek(0)
        f6=f2.read()
        print(f6)
        f1.close()
        f2.close()

结果

public class HelloWorld{

public  static void main(String []args)
{
  System.out.println("helllo world");
}

}
----------
close file

异常还可以自定义,通过继承Exception,还可以主动引起异常,还可以设置断言

通过raise触发异常,但是需要处理异常
raise [Exception [, args [, traceback]]]


import math
def getException(lev):
    if lev<0:
        raise Exception('invalid lev')

def getSqrt(num):
    try:
        getException(num)
        i=0
        y=math.sqrt(num)
        print('{0}*{1}={2}'.format(y,y,num))
    except Exception as e:
        print('error',e)

自定义异常,需要面向对象的知识点.


class  FileException(Exception):
    def __init__(self,arg):
        self.arg=arg
    def __str__(self):
        return repr(self.arg)

try:
    raise FileException('\home')
except FileException  as e:
    print('error ',e.arg)

结果是:


IPython 6.2.1 -- An enhanced Interactive Python.
error  \home

时间好快啊,快点结束python,我准备玩Java了,这才是我主要的方向.

参考文献
Python3 错误和异常

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消