A little knowledge about exception capture - try, except are written inside and outside the function

This article mainly explains the two situations when try, except and functions are used in combination

1 try, excpt inside a function

As we all know, the try and except statements are used to catch exceptions to enhance the robustness and stability of the program, because the following code can still be executed normally after the exception is caught, which is much better than the program throwing an error. Let's look at the following piece of code:

def demo1():
    try:
        print('我正在执行demo1函数')
        raise Exception('查看报错是否返回到函数调用处')
        # int(input('请输入一个整数: '))
    except Exception as result:
        print('我进来了except里')
        # raise result


def demo2():
    return demo1()


try:
    print(demo2())
except ValueError:
    print('请输入正确的整数')
except Exception as result:
    print(f'未知错误{
      
      result}')

insert image description here
After the break point, you can see the code execution sequence: 1 11 15 16 12 outputs the first and second sentences 12 16 outputs None. It can be seen that the code executes print('I am executing the demo1 function') in demo1, and then executes raise Exception('Check whether the error is returned to the function call'), because the exception is actively thrown, so it naturally enters In the exception capture of the sixth sentence, the seventh sentence is then executed. Then I returned to the 12th sentence of the function call. At this time, there is no return after demo1 is executed, so the 12th line is actually return None. Then execute the demo2 function again, just stop at the 12th line, and then return to the function call At line 16, because the return None written in demo2, the final output is the result after demo2 is executed, None.

It should be noted here that

(1) If you write try and except in the function, you should pay attention that raise must be written in both try and except. Otherwise, once an error occurs, the function neither returns anything nor returns the error that occurred, and the function call receives None. It is equivalent to executing a function without doing anything. Nothing useful was returned, nor was an error message returned.
(2) If try and except are written in the function, then the program reports an error in the execution of try or uses raise to actively throw an exception, which can be captured in except Exception as error. Then some people may think, isn’t that nonsense, the error reported in try must have gone to except, but if try and except are outside the function, then it will not go to except. Instead, go back to the function call.
insert image description here
It can be seen that when line 8 is released, the function execution sequence is 1. 11 15. 16 12 After the output statement, 12 stays for a while 16 17. 19. 20. That is, after demo1 is executed, demo1 returns the error report to the place where the calling function is called, that is to say, in demo2, it is actually like this: return 'Check whether the error message is returned to the function call', that is, the result thrown by demo1 is passed to demo2. Then demo2 is executed and returns to line 16 of the function call. An error occurs in try, and it goes to except. The first except error type does not match, so it goes to the second except, so the error message in demo1 is finally passed. 20 lines are given, and an error message is printed.

2 try, except outside the function

try:
    def demo1():
        print('我正在执行demo1函数')
        raise Exception('查看报错是否返回到函数调用处')
        # int(input('请输入一个整数: '))
except Exception as result:
    print('我进来了except里')
    raise result


def demo2():
    return demo1()


try:
    print(demo2())
except ValueError:
    print('请输入正确的整数')
except Exception as result:
    print(f'未知错误{
      
      result}')

insert image description here
After executing line 9, the code directly jumps to line 17, because when try is written outside the function, the exception is transitive, and it will directly return to the calling function without going to except.
Then it returns to line 21 where demo2 was called for the first time. Because there will be an error return when executing line 21, (it is also because there is an error, so nothing is returned. Returning None means that the function has not reported an error, and there is no return value, that is, it returns None. If it does not even return None, it means an error is reported. ) So I went to except, and after matching the exception type, an unknown error was output...

Guess you like

Origin blog.csdn.net/simpleness_/article/details/128007831