【问题标题】:Try... catch: test if statement is trueTry...catch:测试语句是否为真
【发布时间】:2015-08-13 06:16:31
【问题描述】:

我想用Try... Catch方法测试我的十进制加法是否小于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... else!

【问题讨论】:

  • 为什么要抛出异常?
  • 因为我想在我的控制台之后做一些事情,而且我不想使用 if... else。另外我想看看异常是否包含我的 Maxvalue 或 MINVALUE 的值,但这不是重点,我只想知道我如何在 try 块中编写 Things。
  • if (RESULT_MINVALUE > Add || Add > RESULT_MAXVALUE) throw new Exception("error");应该这样做。
  • 使用异常控制程序流is an awful idea.
  • 我不确定您是否理解异常的定义。如果您是编程新手,@UweKeim 是正确的,我建议您不要养成这个坏习惯。

标签: c# exception try-catch decimal between


【解决方案1】:

这取决于您使用的语言,但约定是 try 块包含可以抛出异常的语句,并且抛出的异常由 try 之后的 catch() 块捕获。您需要明确抛出异常才能被捕获。

看起来您正在使用 C#。考虑阅读https://msdn.microsoft.com/en-us/library/0yd65esw.aspx,了解有关 C# 中的 try-catch 语句的更多信息。

可能没有必要在您的情况下使用例外。考虑使用 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.
    }
}

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

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多