try exception異常キャプチャ多重使用について


try exception finally関数内部異常
msg = ""
def test():
    try:
        raise Exception("      ")
    except NameError:
        pass
    try:
        print("test")
    except Exception:
        pass


def main():
    try:
        test()
        print("main")
    except Exception:
        print("not now")

main() 

関数内部未取得異常は外層異常によって取得され、関数内部コードは実行されません.
PS F:\workspace\Template> python .\try.py
not now

関数内部の異常がキャプチャされると、キャプチャされません.
def test():
    try:
        raise Exception("      ")
    except Exception:
        pass
    try:
        print("test")
    except Exception:
        pass


def main():
    try:
        test()
        print("main")
    except Exception:
        print("not now")

main() 

コード異常がキャプチャされ、実行が続行されます.
PS F:\workspace\Template> python .\try.py
test
main

例外キャプチャネスト
異常がキャプチャされるとコードの継続実行に影響せず、外層は異常をキャプチャしないが、try内部コードが異常をトリガした後は実行を継続しない
def test():
    try:
        try:
            print("in1")
            raise Exception("      ")
        except Exception:
            pass
        print("in2")
    except Exception:
        print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
in2
def test():
    try:
        try:
            print("in1")
            raise NameError("      ")
            print("try in2")
        except Exception:
            raise NameError()
            pass
        print("in2")
    except Exception:
        print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
out

本質的に異常をトリガすると運転を継続しないので、できるだけtryを細かく書く.