我目前有以下代码,正是我想要的方式在异常上引发错误:
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)
但它似乎不起作用
答案 0 :(得分:1)
尝试捕获错误的类型而不是解析错误的文本。
更多信息可以在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'
ValueError 是您需要捕获的错误类型。
更现实的是,您可以将未捕获的错误类型确定为程序中的类型,并(有希望)在测试过程中识别它们:
>>> 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;
}
直接从此处复制: Microsoft try-catch (C# Reference)