简体   繁体   English

从Python 3的try-catch块内部退出脚本

[英]Exit script from inside of try-catch block in Python 3

I'm trying to exit a script from inside a try: except: block except it just goes on to the exception case. 我试图从try: except:块内部退出脚本,除了它会继续处理异常情况。

None of these... 都不是...

try:
    exit()
except:
    pass()

try:
    quit()
except:
    pass

import sys
try:
    sys.exit()
except:
    pass

...exit my script, they just go on to the except case. ...退出我的脚本,他们只是继续进行例外情况。

How would I exit my script from inside one of these blocks? 如何从这些块之一退出脚本?

All of these examples raise the SystemExit exception and you are catching that exception, a blank except clause will catch all exceptions. 所有这些示例都引发SystemExit异常,并且您正在捕获该异常,空白的except子句将捕获所有异常。

This is the reason why you should always specify the exception you intend to catch or at least use except Exception eg 这就是为什么您应该始终指定要捕获或至少使用的except Exception例如except Exception

try:
    exit()
except Exception:
    pass

try:
    quit()
except Exception:
    pass

import sys
try:
    sys.exit()
except Exception:
    pass

With that change in place, all of you examples will cause your Python app to exit 完成该更改后,所有示例都将导致您的Python应用退出

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

相关问题 将 python try-except(或 try-catch)代码块转换为 VBA 以用于基本的 excel-selenium 应用程序 - converting python try-except (or try-catch) code block to VBA for basic excel-selenium application Python DBusGMainLoop在线程内部并尝试捕获块 - Python DBusGMainLoop inside thread and try and catch block Python 在 lambda 中尝试 Catch 块 - Python Try Catch Block inside lambda Python FTP 检索中断 FOR 循环。 我用 try-catch 块修复了它。 为什么它有效? - Python FTP retrieve breaks the FOR loop. I fixed it with try-catch block. Why does it work? 为什么我能够从 try-catch 外部访问在 Python 中的 try-except 中定义的变量? - Why am I able to access a variable that was defined in a try-except in Python from outside the try-catch? Try-Catch 与 Beatifulsoup - Try-Catch with Beatifulsoup 如何从它的 try catch 块内部中断 for 循环? - How to break for loop from inside of its try catch block? Try-Catch Exception 在 OpenCV-python 中不起作用 - Try-Catch Exception won't work in OpenCV-python 如何在 Python 中的 if/else 语句中退出 try/except - How to exit from a try/except inside of an if/else statement in Python 捕获异常并继续 Python 中的 try 块 - Catch exception and continue try block in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM