我可以在同一个 catch 中包含多种类型的异常吗?

use*_*517 2 .net c#

在 C# 中,同一个 catch 中可以有多种类型的异常吗?我只是想如果有可能做这样的事情,我感谢任何帮助

try
{
}
catch (ArgumentException || FormatException x)
{
  // do something....
}
catch(Exception x)
{
  throw;
}
Run Code Online (Sandbox Code Playgroud)

egl*_*ase 6

在 C# 7.0 及更高版本中,您可以执行此操作(模式匹配):

try
{
    // code that may throw an exception
    int x = int.Parse("abc");
}
catch (Exception ex) when (ex is FormatException || ex is OverflowException)
{
    // code to handle FormatException and OverflowException
    Console.WriteLine("Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

来源

  • 或者甚至是 `catch (Exception ex) when (ex is FormatException or OverflowException)` (2认同)