I am fairly new to java esp. to some of the coding practices. I have a situation where a method throws a NullPointerException and the calling method catches it.
try {
String test = Class.method(arg)
}
catch (Exception ex) {
...
}
public String method(arg){
String str;
...
if(str == null) throw(exception)
return str;
}
Now some method inside Class.method(arg) throws a NullPointerException and it gets caught in the above catch (like above). Instead I want to do something like:
if (test == null) { do something else }
inside the try block.
What is the best way to handle this? Can I remove the throw inside method and make it return null?
You should catch Exception in
method(arg)and returnnullincase of any exception.Sample Program:
Now you can change method to something like this, it all depends on your requirement: