I have a method using throws, inside is two if/else statements, the if statement tests a condition and then throws an exception if it fails, the problem is of course is that if the first if/else block fails my second never gets executed, is there an alternative way to approach this problem?
EDIT (Further Information)
My code is checking whether a person object has the correct first name Test 1, or the correct surname Test 2, if not throw exception A or B, code further on then adds the person into a group if they pass both conditions
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
}
}
Based upon your description, I am thinking that you could change to
if(Test1)
{
if(!Test2)
{
throw new Exception B
}
// Do some work here
}
else
{
throw new Exception A
}
Another way to consider is by creating methods
bool test1 = correctFirstName (fname);
bool test2 = correctLastName (lname);
if (test1 && test2)
{
// do some stuff
}
else {
if (!test1) // throw ExceptionA
else // throw ExceptionB
}
Something like this should work. I would of course recommend not using generic Exception, but I would also not use two different types of exceptions as your original code implied.
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);
}
}
看来该任务是不可能的,发给我的指令没有说明要触发一个Exception或另一个我必须注释掉代码。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.