试一试. .Catch:测试if语句是否为真

本文关键字:是否 语句 if Catch 测试 试一试 | 更新日期: 2023-09-27 18:07:33

我想用Try... Catch方法测试我的十进制Add是否小于MAXVALUE且大于MINVALUE。如果数字大于MAXVALUE或小于MINVALUE,代码应该抛出一个异常。

但是我的代码不工作。

    public static decimal Add(decimal number1, decimal number2)
    {
        decimal Add = number1 + number2;
        try
        {
            Add > RESULT_MAXVALUE;
            Add < RESULT_MINVALUE;
        }
        catch(Exception)
        {
            //Do Stuf
        }
    }

我不想用if…别的!

试一试. .Catch:测试if语句是否为真

这取决于您使用的语言,但惯例是try块包含可以抛出异常的语句,抛出的异常由try之后的catch()块捕获。你需要在异常被捕获之前显式地抛出异常。

看起来你在用c#。有关c#中try-catch语句的更多信息,请参阅https://msdn.microsoft.com/en-us/library/0yd65esw.aspx。

在您的情况下可能没有必要使用异常。考虑使用if语句,如下所示:

decimal result = a + b;
if ((result > MAX_VALUE) || (result < MIN_VALUE))
{
    // Do stuff.
}

但是为了更直接地回答你的问题,下面是使用异常的方法:

    decimal result = a + b;
    try
    {
        if ((result > MAX_VALUE) || (result < MIN_VALUE))
        {
            throw new System.ArithmeticException(); // Or make an exception type.
        }
    }
    catch (System.ArithmeticException e)
    {
        // Do stuff.
    }

或者您可能会在Add中抛出异常,但不捕获它。然后调用者就有责任处理异常,或者让程序崩溃。它看起来像这样:

// Adds two numbers.  Throws a System.ArithmeticException if the result
// is greater than MAX_VALUE or less than MIN_VALUE.
public static decimal Add(decimal a, decimal b)
{
    decimal result = a + b;
    if ((result > MAX_VALUE) || (result < MIN_VALUE))
    {
        throw new System.ArithmeticException(); // Or make an exception type.
    }
}

调用者需要在try {} catch中包装Add调用,如果他们期望某些结果大于MAX_VALUE或小于MIN_VALUE(否则,调用者无法捕获异常,程序将崩溃)。