栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python异常处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python异常处理

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

一个最常见的错误

>>> print(a)
Traceback (most recent call last):
  File "", line 1, in 
    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 错误和异常

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/224598.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号