第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

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 错误和异常

點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消