获取手动抛出异常的消息

Wol*_*ish 2 c# exception-handling exception

我故意为特定场景抛出异常,但我会隐含地希望以字符串格式获取错误消息.我知道以下异常的一个重载是string message,但是如何访问该字符串?

这是相关的片段:

string errMsg;

private void Compress()
{
    if (sourcePath.EndsWith(".zip"))
    {
        throw new FileLoadException
                   ("File already compressed. Unzip the file and try again.");
        errMsg = //I want the above string here
    }
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*afa 8

你的意思是这个:?

try
{
    throw new FileLoadException
               ("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
    errMsg = ex.GetBaseException().Message;
}
Run Code Online (Sandbox Code Playgroud)

  • @Wolfish虽然有一个教训:没有愚蠢的问题.你不知道什么,不要求更多而不是更少,这就是stackoverflow即将问你不知道的问题/找到答案. (3认同)
  • 这正是我所寻找的.请原谅我,如果这是一个愚蠢的问题,我以前学习C#的教学内容并没有涵盖很多错误处理. (2认同)