简体   繁体   English

捕获异常时sys.exit()不会退出程序

[英]sys.exit() does not exit program when catching exceptions

This program checks molecular formulas. 该程序检查分子式。 I want the program to exit as soon as it detects an error in a formula. 我希望程序在检测到公式中的错误时立即退出。 For example, the formula "a", is incorrect. 例如,公式“ a”不正确。 When I run it through my code: 当我通过代码运行它时:

def readletter():
    if q.peek() in string.ascii_lowercase:
        print(q.peek())
        return q.get()
    else:
        raise Formelfel("Förväntad liten bokstav.")

def readLetter():
    if q.peek() in string.ascii_uppercase:
        print(q.peek())
        return q.get()
    else:
        raise Formelfel("Förväntad stor bokstav.")

def readAtom():
    X = ""
    try:
        X += readLetter()
    except Formelfel:
        print("Missing capital letter at end of row "+getRest())
        sys.exit()
        return

    try:
        x = readletter()
        atom = X+x
    except (Formelfel, TypeError):
        atom = X

    if atom in ATOMER:
        return
    else:
        raise Formelfel("Okänd atom.")

def readGroup():
    if q.peek() in string.ascii_uppercase or q.peek() in string.ascii_lowercase:
        try:
            readAtom()
        except:
            print("Unknown atom at end of row "+getRest())
            sys.exit()

I get this output: 我得到以下输出:

Missing capital letter and end of row a
Unknown atom at end of row

Why is this? 为什么是这样? I called sys.exit() before print("Unknown atom at end of row "+getRest()) so why does it still execute? 我在print("Unknown atom at end of row "+getRest()) sys.exit()之前调用了sys.exit() ,为什么它仍然执行? I want only the first row of the output to be printed. 我只希望打印输出的第一行。

sys.exit raises a SystemExit exception. sys.exit引发SystemExit异常。 You are catching it with your except clause. 您正在使用您的except子句来捕获它。

What you should do instead is catch a more specific class of exceptions, which does not include SystemExit . 相反,您应该做的是捕获更具体的异常类,其中不包括SystemExit

Catching Exception will work: 捕获Exception将起作用:

def readGroup():
    if q.peek() in string.ascii_uppercase or q.peek() in string.ascii_lowercase:
        try:
            readAtom()
        except Exception:
            print("Unknown atom at end of row "+getRest())
            sys.exit()

You can learn more about exceptions and SystemExit in the docs . 您可以在docs中了解有关异常和SystemExit更多信息。


Note that you should ideally catch something more specific than Exception (which is very broad, and may catch exceptions you don't intend to catch). 请注意,理想情况下,您应该捕获比Exception更具体的内容( Exception非常广泛,并且可能捕获您不打算捕获的异常)。

因为在python中,退出事件被作为SystemExit异常处理

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

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