C#使用throw后未输入异常

时间:2019-02-17 00:26:25

标签: c# exception try-catch throw

我是一名初学者,最近我遇到了异常。我在下面做了这个小测试,收到的输出与我期望的输出不同。

static void Main(string[] args)
    {
        ushort var = 65535;
        try
        {
            checked { var++; }
        }
        catch (OverflowException)
        {
            Console.WriteLine("Hello!");
            throw;
        }
        catch
        {
            Console.WriteLine("Here I am!");

        }
    }

我期望程序执行以下操作:

  • 尝试var ++,失败并创建OverflowException;
  • 输入Catch(OverflowException)并输入“ Hello!”;
  • 引发异常并输入catch;
  • 写下“我在这里!”。

但是,我只在屏幕上看到“你好!”。

编辑:感谢那些发表评论的人。我想我已经开始理解。但是,我的困惑源于我正在阅读的这本书:C#4.0。

我可以显示文字,但是是葡萄牙语的。我要解释一下它的含义:“有时,通过多个捕获来传播异常很有用。例如,让我们假设由于“ idade”无效,因此有必要显示特定的错误消息,但是我们仍然需要关闭程序,因为它是全局catch中的那部分。在这种情况下,有必要在执行第一个catch块之后传播异常。没有参数。”

Example from the book

在本书的这个示例中,您可以看到程序员所做的与我所做的相同。至少看起来像这样。我想念什么吗?还是这本书是错的?

希望您能帮助我。谢谢!

3 个答案:

答案 0 :(得分:1)

简而言之,您做错了。让我们访问文档

Exception Handling (C# Programming Guide)

  

可以链接具有不同异常过滤器的多个catch块   一起。捕获块从上至下进行评估   代码,,但对于每个发生异常的异常,仅执行一个catch块   被抛出

尽管没有特别说明您无法捕获已在异常过滤器中重新抛出的异常,但事实是您无法捕获。这将是一场噩梦,并且会有复杂而出乎意料的结果

这就是说,您将需要try catch的另一层(内部或外部)以捕获在catch (OverflowException)中引发的异常

答案 1 :(得分:0)

我经常链接两篇有关异常处理的文章。我个人认为与他们打交道时需要阅读:

https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/

https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

对于这种情况,您不是抛出例外。您正在重新投掷。可以把它想象成一个渔夫在做“捕获和释放”。它可以用于某些情况,例如这次我为卡在.NET 1.1上的人编写了TryParse替代书:

//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;

}

但是根据经验,应该使用“ finally”块之类的东西进行清理工作,而不是捕获并释放。扔到挡块里是很少使用的东西。

答案 2 :(得分:0)

如果嵌套try/catch块,您将获得预期的输出:

static void Main(string[] args)
{
    try
    {
        ushort var = 65535;
        try
        {
            checked { var++; }
        }
        catch (OverflowException)
        {
            Console.WriteLine("Hello!");
            throw;
        }
    }
    catch
    {
        Console.WriteLine("Here I am!");
    }
}