如果抛出异常,会执行什么代码?

Nov*_*Net -5 c# logging exception-handling

try
{
    some code
}
catch()
{
    some code
}
finally
{
    some code
}

try
{
    some code
}
catch()
{
    some code
}
finally
{
    some code
}
Run Code Online (Sandbox Code Playgroud)

我知道如果在第一个try块中抛出异常,那么将执行第一个finally块.第二个最终块怎么样?

此外,如果要在出现异常时向用户显示消息,那么您应该在何处编写该消息,以及如何显示该消息?

仅供参考,我最近在一次采访中被问到了这些问题,并且感到难过.

Mer*_*ham 6

将此代码复制并粘贴到编辑器中.然后玩它,取消注释重新评论各种线条.然后编译并运行代码.继续这样做,直到你对你知道的一切都很满意为止.当你发现所有这些令人困惑的问题时,我建议你这样做,这些问题只是基于流量控制.这就是你学习编程流程控制的方法.

try
{
  Console.WriteLine("try1");
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
catch(ArgumentNullException e1)
{
  Console.WriteLine("catch1");
  Console.WriteLine(e1.ToString());
  // throw;
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
catch(Exception e1a)
{
  Console.WriteLine("catch1a");
  Console.WriteLine(e1a.ToString());
  // throw;
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
finally
{
  Console.WriteLine("finally1");
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}

try
{
  Console.WriteLine("try2");
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
catch(ArgumentNullException e2)
{
  Console.WriteLine("catch2");
  Console.WriteLine(e2.ToString());
  // throw;
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
catch(Exception e2a)
{
  Console.WriteLine("catch2a");
  Console.WriteLine(e2a.ToString());
  // throw;
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
finally
{
  Console.WriteLine("finally2");
  // throw new ArgumentNullException();
  // Console.WriteLine(((string)null).Length); // Will also throw exception
}
Run Code Online (Sandbox Code Playgroud)