【问题标题】:How can I use Throws with multiple if/else conditions?如何在多个 if/else 条件下使用 Throws?
【发布时间】:2018-03-02 00:18:44
【问题描述】:

我有一个使用 throws 的方法,里面是两个 if/else 语句,if 语句测试一个条件,如果失败则抛出异常,问题当然是如果第一个 if/else 块失败我的第二个永远不会被执行,有没有其他方法可以解决这个问题?

编辑(更多信息)

我的代码正在检查人员对象是否具有正确的名字 Test 1 或正确的姓氏 Test 2,如果没有抛出异常 A 或 B,则代码进一步将其添加到组中,如果他们同时通过这两个条件

  Method throws Exception A, Exception B
{
    //Test First name 
    if(Test1)
    {
      If persons firstname is correct, Test1 is true
    }
    else
    {
      throw new Exception A
    }

    //Test Surname
    if(Test2)
    {
      If persons surname is correct, Test2 is true
    }
    else
    {
      throw new Exception B
    }

   //If everything is fine, add the person to a list.
   if (Test1 & Test2)
   {
     Add Person to a list
   }
}

【问题讨论】:

  • 为什么你希望你的程序在抛出异常时继续运行?
  • 抛出异常的全部目的是停止当前方法的执行并向调用者发出出现问题的信号。如果你需要代码继续运行,那么你真的不需要异常
  • 我认为这是XY Problem。您正在使用异常进行流控制,这是一个非常糟糕的反模式。您可能根本不想使用异常,但您没有向我们提供足够的信息来了解。
  • 我的水晶球告诉我你想报告所有错误作为输入验证的一部分。
  • 它正在检查一个人对象是否具有正确的名字 Test 1 或正确的姓氏 Test 2,如果没有抛出异常 A 或 B,则进一步的代码然后将人员添加到组中,如果他们通过这两个条件。

标签: java exception


【解决方案1】:

根据您的描述,我认为您可以更改为

if(Test1)
{
    if(!Test2)
    {
       throw new Exception B
    }
    // Do some work here
}
else
{
  throw new Exception A
}

另一种考虑的方法是创建方法

bool test1 = correctFirstName (fname);
bool test2 = correctLastName (lname);

if (test1 && test2) 
{
    // do some stuff
}
else {
    if (!test1) // throw ExceptionA
    else // throw ExceptionB
}

【讨论】:

  • 怕不行,结果还是一样的,不过还是试试吧!
  • 恐怕你的解释不是很清楚,但是我已经编辑了艾米的答案。这就是你想要的吗?
【解决方案2】:

这样的事情应该可以工作。我当然建议不要使用泛型异常,但我也不会使用原始代码所暗示的两种不同类型的异常。

  Method throws Exception A, Exception B
{
    String errMsg = "";

    //Test First name 
    if(Test1)
    {
      If persons firstname is correct, Test1 is true
    }
    else
    {
      errMsg = "Invalid first name";
    }

    //Test Surname
    if(Test2)
    {
      If persons surname is correct, Test2 is true
    }
    else
    {
      errMsg = "Invalid surname";
    }

   //If everything is fine, add the person to a list.
   if (errMsg.equals(""));
   {
     Add Person to a list
   }
   else
   {
      throw new Exception(errMsg);
   }
}

【讨论】:

    【解决方案3】:

    看来这项任务是不可能的,给我的说明并没有说明为了触发一个异常或另一个我必须注释掉代码。

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多