繁体   English   中英

调用了两个例外中的哪一个?

[英]Which of the two exceptions was called?

如果我有一个例程可以在两个地方抛出ArgumentException,则类似...

if (Var1 == null)
{
    throw new ArgumentException ("Var1 is null, this cannot be!");
}

if (Val2  == null)
{
    throw new ArgumentException ("Var2 is null, this cannot be either!");
}

在我的调用过程中确定抛出两个异常中的哪一个的最佳方法是什么?

要么

我这样做的方式有误吗?

对于此特定方案,您应该使用ArgumentNullException并正确填充其ParamName属性,以便您知道参数为null。

ArgumentException类也支持相同的属性,但是您应该使用可用的最特定的异常类型。

使用这些类型的异常时,在使用接受消息和参数名称的构造函数时也要小心。 在每种异常类型之间切换顺序:

throw new ArgumentException("message", "paramName");

throw new ArgumentNullException("paramName", "message");

将第二个参数中的变量名称(Val1,Val2等)传递给ArgumentException构造函数。 这将成为ArgumentException.ParamName属性。

您的调用函数应该不在乎引起异常的行。 在这两种情况下,都将引发ArgumentException ,并且应以相同的方式处理两者。

使用构造函数ArgumentException(string,string)定义哪个参数为null。

if (Var1 == null) {
  throw new ArgumentException ("Var1 is null, this cannot be!","Var1");
}

if (Val2  == null){
  throw new ArgumentException ("Var2 is null, this cannot be either!","Var2");
}

您应该问自己的更大问题是为什么? 如果您试图从中消除某种逻辑,那么异常通常是一个不好的选择。

相反,您应该具有一个返回类型(或out / ref参数),该返回类型将设置有某种标志/值,您可以从调用代码中检测该标志/值以确定错误是什么,并消除该错误。

如果您坚持使用异常,那么在这种情况下, ArgumentNullException具有一个构造函数,该构造函数采用参数名称和异常消息 您可以引发异常,然后在捕获异常时,访问ParamName属性以确定导致异常的参数的名称。

您实际上没有提供足够的信息来回答您的问题。 显而易见的答案是查看异常消息,但我想这不是您要查找的内容。

如果能够以编程方式区分它们真的很重要,则可以使用另一个异常,或者至少使用当前异常的构造函数的paramName属性。 这将为您提供更多相关信息。

但是, 使用自己的异常类型是确保您在特定情况下捕获异常的唯一方法 由于ArgumentException是框架的一部分,因此您调用的其他内容可能会将其抛出,这将导致您进入同一catch块。 如果您创建自己的异常类型(针对两种情况,一种或两种情况),这将为您提供一种处理特定错误的方法。 当然,从您的示例来看,在调用函数开始之前先检查一下Val1Val2是否为null似乎更为简单。

好吧,特别是对于ArgumentException,您有一个参数存在问题的参数:

throw new ArgumentException("Var1 is null, this cannot be!", "Var1");

从更一般的意义上讲,您通常会执行类似的操作,例如使用不同的(可能是自定义的)异常类型,然后调用代码可以具有不同的catch块

public class MyCustomException1 : ApplicationException {}
public class MyCustomException2 : ApplicationException {}


try
{
 DoSomething();
}
catch(MyCustomException1 mce1)
{
}
catch(MyCustomException2 mce2)
{
}
catch(Exception ex)
{
}
try
        {
            //code here
        }
        catch (ArgumentException ae)
        {
            Console.WriteLine(ae.ToString());
        }

控制台中的输出将告诉您所输入的消息。

ArgumentExceptions您始终可以包括引起异常的参数名称(这是另一个构造函数 )。 当然,我假设您真的想知道哪个为空,在这种情况下,您可能应该使用ArgumentNullException

如果这是用于要确保显示正确的异常消息的测试用例,则我知道NUnit对ExpectedException属性具有ExpectedMessage关键字。 否则, ArgumentNullExceptionArgumentNullException ,您的应用程序应将它们全部相同。 如果需要更多详细信息,请创建自己的异常类并使用它们。

因此,您可以测试以下内容:

[ExpectedException(typeof(ArgumentNullException), ExpectedMessage="Var1 is null, this cannot be!"]
public void TestCaseOne {
    ...
}

[ExpectedException(typeof(ArgumentNullException), ExpectedMessage="Var2 is null, this cannot be either!"]
public void TestCaseTwo {
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM