CurlyCream CurlyCream - 4 months ago 9
Java Question

Multiple if statements within try block

I have try catch block and am writing multiple if else statements. I see that , when the if condition is false, the control is not going to else instead it goes to a catch block. Here is my code,

try
{
if(fname.contains("javier")
{

if(lname != null || lname.isEmpty())
{
employee.setlname("perez");
}
else
{
employee.setlname("No last name");
}
sysout(name);
}

else
{
--------------
-------------
}
}
catch(Exception e)
{

print("caught exception");

}


Now, whenever my if(lname != null || lname.isEmpty()) is false, it goes to the catch block.

Answer

Should be

lname != null && !lname.isEmpty()

... in your conditional construct instead of the or (||).

The or condition that you've applied means that it will check both conditions (null and isEmpty()) and you'll get a NullPointerException if lname is null, as lname != null failing will then go straight on to check if it's empty thereafter.

You should handle your exceptions better than just writing out "caught exception". Write out the stack trace and you'll be able to debug these kind of issues yourself.

If it gets past the above block and drops into the else block, then the problem is that your employee object is null and you need to initialize that object prior to calling this code.