简体   繁体   English

Python:如何在try / except块之外使用错误?

[英]Python : How to use an error out of a try/except block?

I have this try block in my code : 我的代码中有这个try块:

try:
    installation('isc-dhcp-server')
except:
    print('Oops an error...')
    sys.exit(8)

Here in a try/except block the sys.exit(8) will just exit this block and keep an error with code "8". 在try / except块中,sys.exit(8)将仅退出此块,并使用代码“ 8”保留错误。 This is just what I want. 这就是我想要的。 Now I want to use this except somehere else in a code to avoid somes parts link to this setup. 现在,我想在代码中的其他地方使用它,以避免某些部分链接到此设置。 How can I do that ? 我怎样才能做到这一点 ?

I try to put the error in a variable with : 我尝试将错误放入变量中:

except Exception as NameofError:

And use NameofError with a if statement but this var is not defined in the local space (I think) so I can't use it. 并将NameofError与if语句一起使用,但是该变量未在本地空间中定义(我认为),因此我无法使用它。

Just initiate a variable before the try-catch block and assign the exception to it 只需在try-catch块之前启动变量,然后为其分配异常

caught_error = None
try:
    # some error throwing func
except Exception as e:
    caught_error = e
    # your error handling code
print(caught_error)

Edit: However, if you still have sys.exit() in your catch block you probably won't have the chance to do anything to the exception given that your program will be terminated already. 编辑:但是,如果您的catch块中仍然有sys.exit() ,则您的程序可能已经终止,您可能将没有机会对异常做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM