如何在多个if / else条件下使用Throws?

时间:2018-03-02 00:18:45

标签: java exception

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

编辑(更多信息)

我的代码正在检查一个人物对象是否具有正确的名字Test 1,或正确的姓氏Test 2,如果不是抛出异常A或B,则进一步代码然后将该人员加入一个组中,如果他们通过了两个条件< / p>

  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
   }
}

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

这样的事情应该有效。我当然建议不要使用通用的Exception,但我也不会使用两种不同类型的异常,就像你原来的代码所暗示的那样。

  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);
   }
}

答案 2 :(得分:0)

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

相关问题