手动抛出异常的信息获取

3

我有意为特定情况抛出异常,但我希望隐式地以字符串格式获取错误消息。我知道以下异常的其中一个重载是 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
    }
}

1
该代码无法到达。"errMsg = //我想在此处放置上述字符串" - Selman Genç
1
正如您在评论中提到的,您对错误处理还不熟悉。您应该考虑的一件事是,如果在那个位置真的需要异常(如果它在同一个if语句中,您需要捕获它,那么问题是您是否真的需要异常,或者只是要设置一个字符串errMsg)。 - Thomas
@Thomas 我会说不需要,但我目前所有的项目都是关于学习C# - 包括学习如何处理错误。理想情况下,我只需使用字符串中断函数即可。 - Wolfish
1
就像我之前所说的,由于你对异常处理还不熟悉,所以那个注释才会出现。我已经认为在这种情况下不需要使用异常,并想提醒你在学习何时何地使用/引发异常以及何时/何地不使用时要注意。当我使用异常时,我总是会问自己一个思考过程:“我真的需要在那里使用异常吗,还是只需要一个字符串即可?”只有在你希望调用进程知道发生了什么并且需要立即停止被调用方法的处理时,才需要使用异常。 - Thomas
5个回答

8
你的意思是这个吗?
try
{
    throw new FileLoadException
               ("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
    errMsg = ex.GetBaseException().Message;
}

2
这正是我在寻找的。如果这是一个愚蠢的问题,请原谅我,我用来学习C#的教学内容没有涵盖太多错误处理。 - Wolfish
3
重要提示:没有愚蠢的问题。你不知道某些事情,发问不多不少,这也是Stackoverflow的宗旨——提出你不懂/找不到答案的问题。 - Thomas
1
@Wolfish 让我这样说:大多数投反对票的人甚至不告诉我他们为什么投反对票(因此我感觉有些人只是为了投反对票而投)。那些给出理由的人我会考虑并相应修改我的问题(或者如果是回答被投反对票,我会修改我的回答)。那些不给出理由的人我倾向于忽略,因为没有任何指示可以让我更好地提出问题(通常只是一些形式上的错误,比如没有代码示例等)。 - Thomas
因此,问题本身并不愚蠢,只有实现可能存在缺陷。 - Thomas

2
您无法访问字符串THERE。我稍微解释一下:
string errMsg;

private void Compress()
{
    if (sourcePath.EndsWith(".zip"))
    {
        throw new FileLoadException
                   ("File already compressed. Unzip the file and try again.");
        // The following line is unreachable as the throw ends the function and gets the exception to the calling function as there is no try catch block to catch the exception.
        errMsg = //I want the above string here
    }
}

一种可能的方法是在你想要设置变量的方法中使用try/catch捕获异常:

private void Compress()
{
    if (sourcePath.EndsWith(".zip"))
    {
        try
        {
            throw new FileLoadException
                       ("File already compressed. Unzip the file and try again.");
        }
        catch (Exception e)
        {
            errMsg = e.Message;
        }
    }
}

或者在调用方法中捕获异常:
try
{
    Compress();
}
catch (Exception e)
{

}

无论使用何种方法,e.Message都会以字符串形式提供异常的信息。

1

尝试捕获异常并设置消息是没有意义的,除非你重新抛出它。

try
{
    throw new FileLoadException("File already compressed. Unzip the file and try again.");

}
catch (Exception ex)
{
    errMsg = ex.GetBaseException().Message;
    throw;
}

我宁愿这样做

private void Compress()
{
    if (sourcePath.EndsWith(".zip"))
    {
        errMsg = "File already compressed. Unzip the file and try again.";
        return;
    }
}

我会记住这个,留待未来的项目使用。不过,这个项目也是为了教育自己,所以我正在探索函数和方法。 - Wolfish

0

我不确定我完全理解了,但如果您想要从异常中获取消息,您可以捕获它并检查Exception.Message

        try
        {
            throw new FileLoadException("Custom error string");
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
        }

0

这里应该有一个解决方案:)

        if (sourcePath.EndsWith(".zip"))
        {
            FileLoadException ex = new FileLoadException("File already compressed. Unzip the file and try again.");
            errMsg = ex.ToString();
        }
        Console.WriteLine(errMsg);

抛出你所创建的异常,我会像这样做:

    static string sourcePath = "test.zip"; //hardcoded file
    static string errMsg; //the error string

    private static void Compress()
    {
        try
        {

            if (!sourcePath.EndsWith(".zip"))
            {
                Console.WriteLine("File doesn't end with zip so it can be compressed"); //if it does not end with zip its rdy for compressing and here you can indput your code to compress
            }
            else
            {
                throw new Exception(); //instead of using try catch you can also generate the code in here instead of throwing an exception.
                                       //when throwing a new exception you make it stop the if setting and jump into the catch if you use break it wont enter the catch but instead it will just jump over it.
            }
        }
        catch 
        {
            //Here it will generate the custom exception you wanted and put it inside the errMsg
            errMsg = new FileLoadException("File already compressed. Unzip the file and try again.").ToString();
            Console.WriteLine(errMsg);
        }

当然,这是在控制台中编写的,所以我使用了console.writeline。你可以简单地更改它们。

抛出异常怎么样,而不仅仅是创建它? - Andrey Korneyev
通常我会像上面所有人一样使用try catch,但我理解你的问题是你想要FileLoadException在你的errMsg中,这个代码可以实现吗?也许可以重写成一行,但我把它写成了多行以便你理解。 如果你的if语句不会崩溃,那么它就不会进入catch,所以如果你使用if语句,它只会检查文件是否以zip结尾,它永远不会进入catch。 基本上,我将用新的方式编辑它,来抛出异常。 - BlackStarHH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接