Python 为什么我的异常消息不随if语句更改
我目前有以下代码,它会按照我的要求在异常上抛出错误:Python 为什么我的异常消息不随if语句更改,python,python-3.x,exception,error-handling,try-catch,Python,Python 3.x,Exception,Error Handling,Try Catch,我目前有以下代码,它会按照我的要求在异常上抛出错误: 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 b
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)
但它似乎不起作用尝试捕获错误类型,而不是解析错误文本
更多信息可以在上找到,但要彻底了解(因为我在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'
原始的(完全无用的)答案保存在这里供子孙后代使用(因此评论是有意义的)。。。 尝试捕获错误类型,而不是分析错误文本 e、 g } 直接从此处复制:
如果str(e)=……,请尝试
,
您不应该根据异常消息检查异常,而应该根据异常类型检查异常。在您的示例中,您应该添加另一个,除了ValueError
@Tomerikoo,感谢您指出我的原始答案使用了错误的语言,并提供了一条注释以获得OP。我把我的答案翻译成Python,并详细阐述了一些内容。@Tomerikoo是的,是的。我现在要羞愧地低下头去隔离我自己。很抱歉,我花了很长时间才回来看你的回复。我现在就修。我不确定你的肤色是否好看!你的编辑真的很好+从我这里得到1。我可能只想补充几句,使用除(无明确错误)之外的广泛的(无明确错误)是不可取的,被认为是不好的做法。除此之外,还有很好的解释和例子@Tomerikoo-Hah,我同意这是一种不好的做法,并且在上面的评论中有这样的说法,除了,但我把它删掉了,因为我认为我离问题太远了,可能会把人搞糊涂。如果你认为它没有掩盖问题,请随意添加。
>>> 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
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;