exception handling of Python

本文深入探讨了Python中的异常处理机制,包括如何捕获并处理多种类型的异常,如IOError、ZeroDivisionError等,并展示了如何使用try-except-else-finally语句块来控制程序流程,确保即使遇到错误也能优雅地继续运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#exception handling of Python
#how to do with the exception  just like java
#raising exceptions
#multiple exceptions
#geniric exception
#ignoring exception  how about pass


#raising excpetion
def readFile(filename):
    if filename.endswith('txt'):
        fh = open(filename)
        return fh.readinto()
    else: raise  ValueError('filename must be ended with txt')

# ignoring exception  how about pass


def ignorexce():
    counter = 0
    try:
       fh=open("file.txt")  #  here can give an example of file not exists ,and then the finally block will get counter equal 1  ,but now it will be 0
       print  'ignor'  # csn not printlog
    except:
        pass   # will not print anything of error log
        counter += 1
        print  "error" # print this error
    finally:  # the finally block
        print "all work was done by Ethan"
        print ('calculate the error times %s ' % counter)




def main():
    try :
        fh = open("file.txt")
        x = 1/0
    except IOError as e:
        print ('this my log :', e ) # if not found open file will print this log error in cousolut
    except ZeroDivisionError as e :
        print("u r divising by zero : ," ,e)
    except:   # this is call generic exceptions ,this will catch everything ,this will it called generic
        print ("unkown reasons")
    else:
        print("this will not print any way")
    print "all done " # from here can know the excpetion will not break donw the process ,it will goes on
    try:
        for line in readFile("filename.tx1t") :print line   # file not ended with txt will get raising exceptions
    except IOError as e1:
        print ('big eror :',e1)
    except ValueError as e :
        print ('this message from raising exceptions : ',e)

    ignorexce()
main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值