如果声明抛出异常?

TrN*_*TrN 20 c# exception-handling exception

嗨,我想问,因为我不确定它是否是使用异常的私人:

public int Method(int a, int b) {
   if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
   //do stuff... 
}
Run Code Online (Sandbox Code Playgroud)

if语句之后可以抛出Exception吗?或者我应该总是使用try-catch与异常一起使用?

Fil*_*erg 25

这完全有效.这正是用于检查逻辑中的"例外"的异常,这些事情本来就不是假设的.

捕获异常的想法是,当您在某处传递数据并对其进行处理时,您可能并不总是知道结果是否有效,即您想捕获的时间.

关于你的方法,Method当你调用它时,你不想捕获内部而是实际上,这是一个例子:

try
{
    var a = 10;
    var b = 100;
    var result = Method(a, b);
}
catch(ArgumentException ex) 
{
    // Report this back to the user interface in a nice way 
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,a小于b,所以你可以在这里得到一个例外,你可以相应地处理它.


dle*_*lev 10

在这种情况下,您不希望捕获异常.你扔掉它是为了提醒来电者他们调用你的方法时犯了错误.自己捕捉它可以防止这种情况发生.所以是的,你的代码看起来很好.


T.J*_*der 8

那很好.你抛出异常,而不是捕获/处理它,所以你不需要一个try/catch块.


cry*_*ted 6

这是完全有效的,即使使用构造函数也可以使用相同的构造.但你不应该做的

   public int Method(int a, int b)
    {
        try
        {
            if (a < b)
                throw new ArgumentException("the first argument cannot be less than the second");
        }
        catch (Exception)
        {

        }
        return 0;

    }
Run Code Online (Sandbox Code Playgroud)