Home > Backend Development > Python Tutorial > An article to help you understand Python exception delivery and custom exceptions

An article to help you understand Python exception delivery and custom exceptions

Release: 2023-07-25 15:40:52
forward
944 people have browsed it

1. Exception delivery

1. Try nested

import time


try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
    finally:
        f.close()
        print('关闭文件')
except :
   print("没有这个文件")
finally:
    print("最后的finally")


# 这是test.txt文件中读取到信息
Copy after login

Running results :

An article to help you understand Python exception delivery and custom exceptions

2. Function nesting call

   def test1():
        print("----test1-1----")
        print(num)
        print("----test1-2----")




    def test2():
        print("----test2-1----")
        test1()
        print("----test2-2----")




    def test3():
        try:
            print("----test3-1----")
            test1()
            print("----test3-2----")
        except Exception as result:
            print("捕获到了异常,信息是:%s"%result)


        print("----test3-2----")




    test3()
    print("------华丽的分割线-----")
    test2()
Copy after login

Run results:

An article to help you understand Python exception delivery and custom exceptions

Small summary:

  1. If the try is nested, then if the inner try does not catch the exception, the outer try will receive the exception and then process it. If the outer try still does not catch it, then it will be passed on.

  2. If an exception is generated in a function, such as function A----> function B----> function C, and The exception is generated in function C, then if the exception is not handled in function C, then the exception will be passed to function B. If function B has exception handling, it will be executed according to the processing method of function B; if Function B also has no exception handling, so the exception will continue to be passed, and so on. . . If all functions are not handled, then the default handling of the exception will be performed at this time.

二、抛出自定义的异常

你可以用raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是Error或Exception类的子类

下面是一个引发异常的例子:

class ShortInputException(Exception):
    '''自定义的异常类'''
    def __init__(self, length, atleast):
        #super().__init__()
        self.length = length
        self.atleast = atleast


def main():
    try:
        s = input('请输入 --> ')
        if len(s) < 3:
            # raise引发一个你定义的异常
            raise ShortInputException(len(s), 3) #自定义异常长度为3。
            
    except ShortInputException as result:#x这个变量被绑定到了错误的实例
      
        print(&#39;ShortInputException: 输入的长度是 %d,长度至少应是 %d&#39;% (result.length, result.atleast))
    else:
        print(&#39;没有异常发生.&#39;)


main()
Copy after login

运行结果:

An article to help you understand Python exception delivery and custom exceptions

An article to help you understand Python exception delivery and custom exceptions以上程序中,关于#super().init()代码的说明:

这一行代码,可以调用也可以不调用,建议调用。

因为__init__方法往往是用来对创建完的对象进行初始化工作,如果在子类中重写了父类的__init__方法,即意味着父类中的很多初始化工作没有做,这样就不保证程序的稳定了,所以在以后的开发中,如果重写了父类的__init__方法,最好是先调用父类的这个方法,然后再添加自己的功能。


三、异常处理中抛出异常

class Test(object):
    def __init__(self, switch):
        self.switch = switch #开关
    def calc(self, a, b):
        try:
            return a/b
        except Exception as result:
            if self.switch:
                print("捕获开启,已经捕获到了异常,信息如下:")
                print(result)
            else:
                #重新抛出这个异常,此时就不会被这个异常处理给捕获到,从而触发默认的异常处理
                raise


a = Test(True)


a.calc(11,0)


print("----------------------华丽的分割线----------------")


a.switch = False
a.calc(11,0)
Copy after login

运行结果:

An article to help you understand Python exception delivery and custom exceptions


4. Summary

This article is based on the basics of Python and explains it in detail It explains what kind of handling methods should be adopted when encountering various exceptions during operation, and provides effective solutions to various exceptions. Through the actual operation of small projects and the display of operation results, problems can be better solved. I hope it can help you learn Python better.

The above is the detailed content of An article to help you understand Python exception delivery and custom exceptions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template