继续获得正确捕获的例外情况

时间:2013-10-11 13:21:07

标签: c# exception-handling arguments try-catch

我需要一些小问题的帮助。 我有2个字符串需要按顺序 Task Scheduler中的参数框。但我想抓住当有人意外转换它们时发生的System.FormatException

但无论发生什么事,我都会遇到同样的错误。我还添加了一个捕获,以防其中一个或两个都没有被放置。因为如果发生这种情况,将发生System.IndexOutOfRangeException错误。基本上我的代码执行以下操作:

try
{
   //Processing the inputted parameters
}

catch(System.FormatException e)
{
   Console.WriteLine(e.Message);
}

catch(System.IndexOutOfRange.FormatException e)
{
   Console.WriteLine(e.Message);
}

我分别测试了这两个捕获量。但无论哪种方式,我都会收到错误。

我见过一些例子,但这些例子是专门针对某些方法制作的。

如果有人能帮我解决这个问题,我会很感激! :)

修改

目前的捕获:

catch(Exception e)
{
   Console.WriteLine(e.Message);
   streamwriter.Close();
   filestream.Close();
}

修改

错误:

Unhandled exception: System.FormatException: the format of the input string is incorrect.
at System.Number.StringToNumber < NumberBuffer String str, NumberStyles options, NumberFormatInfo info, Boolean & number, parseDecimal >
at System. Number. ParseInt32 < String s, NumberStyles style, NumberFormatInfo info >
at System. Convert. ToInt32 < String value > at LastWriteAccess_Checker. Program. Main < String [] args >

这全都是指代码中的输入参数。一个int转换为string

1 个答案:

答案 0 :(得分:0)

这回答了现在已编辑过的原始问题,因此根据编辑内容可能不是一个合适的答案。

要捕获这两个异常并对它们作出反应,您可以写这个。

catch (Exception ex)            
{                
    if (ex is FormatException || ex is IndexOutOfRangeException )
    {
        Console.WriteLine(ex.Message);
    }
    else
    {
        throw;
    }
}
finally
{
    streamwriter.Close();
    filestream.Close();
}

您可以在catch上放置一个断点,以查看捕获的实际异常是什么。

您应关闭finally块中的资源,而不是catch