I have defined a function:
public MyCar findCar(){
MyCar car = CarManager.findCarById("U983"); //Nullpointer Exception here if no car be found
if(car!=null)
return car;
else
return null;
}
When I invoke the above function in Java, If the above CarManager.findCarById() did not find any car, it returns null, and I try to check in if condition that if it is null return null other wise return the car.
But the findCar() function always stop and raise Nullpointer Exception when findCarById() did not find any car, without go through my if condition. How to get rid of it?
============ findCarById() is a library API I can not modify =================
Throwing or catching NullPointerException is not a really good idea. If you can modify that
findCarById, change it.Otherwise, you can do try-catch here.