gpt4 book ai didi

python - 为什么我的异常消息不会随着我的 if 语句而改变

转载 作者:行者123 更新时间:2023-12-03 07:52:28 25 4
gpt4 key购买 nike

我目前有以下代码,它会按照我想要的方式抛出异常错误:

try:
something ....

except Exception as e:
print(
'You have encountered the following in the main function \n ERROR: {}'.format(e))

但是在某些情况下,如果我遇到特定异常,例如:
invalid literal for int() with base 10: ''

我想将异常中的 e 消息更改为我想要的..我该怎么做?
If e == "invalid literal for int() with base 10: ''":
e = 'my new message'
print(e)



但它似乎没有工作

最佳答案

try catch 错误的类型,而不是解析错误的文本。

更多信息请访问 Handling Exceptions section of Python help但要彻底彻底(因为我最初在 C# 中回答 Python 问题时觉得很愚蠢),您可以使用以下内容来整理您正在寻找的异常类型:

>>> # Create the error
>>> int('3.6')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.6'

在哪里 值错误 是您需要捕获的错误类型。

更现实地说,您可以将 Uncaught Error 类型纳入您的程序并(希望)在测试期间识别它们:
>>> try:
... # something ....
... int('3.6') # for the example, we'll generate error on purpose
... # Assume we've already figured out what to do with these 3 errors
... except (RuntimeError, TypeError, NameError):
... print("We know what to do with these errors")
... # Our generic except to catch unhandled errors.
... except:
... print("Unhandled error: {0}".format(err))

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: '3.6'

确定新的错误类型后,为其添加特定的处理程序:
>>> try:
... # something ....
... int('3.6')
... except (RuntimeError, TypeError, NameError):
... print("We know what to do with these errors")
... # The newly added handler for ValueError type
... except ValueError:
... print("And now we know what to do with a ValueError")
... print("My new message")
... except:
... print("Unhandled error: {0}".format(err))

And now we know what to do with a ValueError
My new message

原始(完全没用)的答案留在这里供后代使用(所以评论很有意义)......

try catch 错误的类型,而不是解析错误的文本。

例如
catch (FileNotFoundException e)
{
// FileNotFoundExceptions are handled here.
}
catch (IOException e)
{
// Extract some information from this exception, and then
// throw it to the parent method.
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;

}

直接从这里复制:
Microsoft try-catch (C# Reference)

关于python - 为什么我的异常消息不会随着我的 if 语句而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60914445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com