![](/img/trans.png)
[英]During handling of the above exception, another exception occurred: Python program
[英]During handling of the above exception, another exception occurred
我有以下 try-except 來捕獲 JSON 解析錯誤:
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e))
為什么During handling of the above exception, another exception occurred
打印出During handling of the above exception, another exception occurred
如何解決?
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 103 column 9 (char 1093)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
<....>
raise Exception('Invalid json: {}'.format(e))
Exception: Invalid json: Expecting ',' delimiter: line 103 column 9 (char 1093)
目前,您在另一個捕獲的異常中引發ValueError
異常時遇到問題。 這個解決方案的推理對我來說沒有多大意義但如果你改變
raise Exception('Invalid json: {}'.format(e))
到
raise Exception('Invalid json: {}'.format(e)) from None
制作你的最終代碼。
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json: {}'.format(e)) from None
您應該獲得捕獲異常的預期結果。
例如
>>> foo = {}
>>> try:
... var = foo['bar']
... except KeyError:
... raise KeyError('No key bar in dict foo') from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
KeyError: 'No key bar in dict foo'
抱歉,我無法向您解釋為什么這特別有效,但它似乎可以解決問題。
更新:看起來有一個PEP 文檔解釋了如何在異常警告中抑制這些異常。
由於您從except
語句內部引發另一個異常,python 只是告訴您這一點。
換句話說,通常您使用except
來處理異常而不是使程序失敗,但在這種情況下,您在已經處理了一個異常的同時引發了另一個異常,這就是 python 告訴您的。
如果這是您想要的行為,那真的沒有什么可擔心的。 如果您想“擺脫”該消息,您也許可以在不引發其他異常的情況下向輸出寫入一些內容,或者僅在不使用try/except
語句的情況下使程序第一個停止。
正如史蒂文所建議的,你可以這樣做:
raise Exception('Invalid json: {}'.format(e)) from e
打印兩個異常,如下所示:
Traceback (most recent call last):
File "tmp.py", line 5, in <module>
raise Exception('Invalid json: {}'.format(e)) from e
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
<...>
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 103 column 9 (char 1093)
或者你可以這樣做:
raise Exception('Invalid json: {}'.format(e)) from None
抑制第一個並且只記錄Invalid json...
異常。
順便說一句,做一些像raise Exception('Invalid json: {}'.format(e))
並沒有多大意義,在這一點上你可以只留下原始異常,因為你沒有添加太多信息給它。
Python 會提醒您,您拋出了一個異常,而另一個正在處理中。 如果這是意外情況,警告會提醒您,以便您了解原始異常。 考慮如下案例:
class Resource:
def close(self):
if cannot_close:
raise Error("Cannot close")
def write_data(self, data):
...
some_function():
try:
res = Resource()
res.write_data("some data")
except Error as e:
res.close()
假設write_data
引發了一個異常,但是close
也出乎意料地這樣做了。 發生這種情況時,很高興了解這兩種例外情況。 在大多數情況下,您想了解write_data
引發的原始異常,但了解來自close
異常有助於您了解close
發生了一些奇怪的事情。
但是對於您的情況,您只是以新的方式重述原始錯誤。 這樣做可以讓您提供更多上下文,例如:
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json from file {}: {}'.format(json_file, e))
這將為您提供未能解析為 JSON 的文件的路徑,這是不會出現在原始異常消息中的有用上下文信息。
因此,要告訴 Python 您實際上是在重新引發原始異常,但要使用更多上下文,您可以from e
添加。
with open(json_file) as j:
try:
json_config = json.load(j)
except ValueError as e:
raise Exception('Invalid json from file {}: {}'.format(json_file, e)) from e
這相當於 Java 中的“異常鏈接”,您可以將原始異常提供給新異常的構造函數。
我已經解決了使用data.get(key)
而不是data[key]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.