C# 用于引发异常的if语句?

C# 用于引发异常的if语句?,c#,exception,exception-handling,C#,Exception,Exception Handling,嗨,我想问一下,因为我不确定使用异常是否合适: public int Method(int a, int b) { if(a<b) throw new ArgumentException("the first argument cannot be less than the second"); //do stuff... } public int方法(inta,intb){ 如果(a这很好。您正在抛出异常,而不是捕获/处理它,因此您不需要为它设置try/catch块。在这种

嗨,我想问一下,因为我不确定使用异常是否合适:

public int Method(int a, int b) {
   if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
   //do stuff... 
}
public int方法(inta,intb){

如果(a这很好。您正在抛出异常,而不是捕获/处理它,因此您不需要为它设置
try/catch
块。

在这种情况下,您不想捕获异常。您抛出异常是为了提醒调用方他们在调用您的方法时犯了错误。亲自捕获它可以防止这种情况发生是的,您的代码看起来不错。

这是完全有效的。这正是异常的用途,用于检查逻辑中的“异常”,以及不应该出现的情况

捕获异常背后的想法是,当您将数据传递到某个位置并对其进行处理时,您可能并不总是知道结果是否有效,也就是您希望捕获的时候

关于您的方法,您不希望捕获内部
方法
,但实际上,当您调用它时,下面是一个示例:

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 
}

在上述情况下,a小于b,因此您可以在此处获得异常,并相应地处理它。

您在此处所做的一切都很正常

arg检查的一种常见模式是将检查/抛出代码包装在一个静态“契约”类中,以确保在验证输入参数时使用一致的异常管理方法


稍微偏离主题,但如果使用.NET 4.0,您还可以查看新功能以验证方法输入和输出。

这是完全有效的,您甚至可以使用构造函数使用相同的构造。 但是你不应该做的是

   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;

    }
public int方法(inta,intb)
{
尝试
{
if(a
你的想法是对的。你可以这样使用你的代码:

void MyMainMethod()
{

    // ... oh, let's call my Method with some arguments
    // I'm not sure if it'll work, so best to wrap it in a try catch

    try
    {
        Method(-100, 500);
    }
    catch (ArgumentException ex)
    {
        Console.WriteLine(ex.Message);
    }

}


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

    //do stuff ...  and return 

}
void mymain方法()
{
//…哦,让我们用一些参数调用我的方法
//我不确定它是否会起作用,所以最好用试一试的方式来包装它
尝试
{
方法(-100500);
}
捕获(参数异常)
{
控制台写入线(例如消息);
}
}
公共整数方法(整数a、整数b)
{
如果(a
这可能有助于彻底了解和解决问题