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

问题描述 投票:0回答:3

我有一个使用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
   }
}
java exception
3个回答
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
}

0
投票

这样的事情应该有效。我当然建议不要使用泛型异常,但我也不会使用两种不同类型的异常,因为你的原始代码暗示了。

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.