NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
Answer from Eng.Fouad on Stack OverflowNullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
java - Catching null pointer exceptions - Stack Overflow
java - Null Pointer exception within a try catch block - Stack Overflow
Is it a acceptable approach to put try catch wherever null pointer exception occurs? - Software Engineering Stack Exchange
Eliminating Null Pointer Exceptions
From my stance, I'm hesitant to consider these two code blocks equivalent in intent. Sure, they go through the same error handling, but that's a developer's decision more than anything else.
To me, the if is testing to see if a value can be used, and if it can't, it's working around the issue. The try...catch block is assuming the value is valid, and if it isn't, it falls through to work around the aberrant behavior.
Exceptions should primarly be considered when aberrant, program-breaking code occurs (divide-by-zero, etc).
No, those code blocks are not the same at all.
In the first code block, you are checking if myVariable is null, and you are doing it at only one point in time. Later on, myVariable may become null and eventually throw a NullPointerException. If this happens, the second code snippet will catch the exception, but the first will not.
Furthermore, the second code snippet will catch NullPointerExceptions that may be thrown from anywhere in the call stack resulting from the carryOn(myVariable) call. This is terrible; you are swallowing an exception operating under the assumption that a particular variable is null when it may be something else entirely.
Use the first code snippet.
You should not use try / catch blocks to eliminate null pointer exceptions. Null pointer exceptions should be passed down, to let programmer know that problem arises and where.
In your case, you are catching IOException, so its not NullPointerException.
Also check what is null that is causing this exception, maybe its mConnection ? or getInputStream() returns null.
From this example, you can also see that its best to not execute lots of methods in one line:
ret = mConnection.getInputStream().read(buffer);
its better to write:
InputStream is = mConnection.getInputStream();
ret = is.read(buffer);
this way you will know from callstack where NPE originated,
if your code is unsafe, like you know you can get nullpointer from some method, then simply check it:
InputStream is=null;
if ( mConnection != null ) {
is = mConnection.getInputStream();
if ( is != null ) {
ret = is.read(buffer);
}
else {
// log error?
}
}
else {
// log error?
}
try {
ret = mConnection.getInputStream().read(buffer);
} catch (Exception e) {
Log.e("your app", e.toString());
break;
}
Should solve the issue
If you're using third party code that is returning null, it's much better to check the return value.
ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
...
}
Edit: Java 8 is out! This should now be
Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());
A NullPointerException is insidious and misleading, because it means you have an error somewhere else, where a variable was set to null without you expecting it to be.
I repeat, the bug isn't where the NullPointerException was thrown, the bug is earlier in your code, where a variable was set to null without you expecting it to be.
Catching the NullPointerException means you're hiding or excusing the actual bug.
In your own code, it is much better to do away with null whereever possible, and for that matter, also mutable variables.
If you get an exception, don't catch it and return null, instead wrap and rethrow the exception.
If you have a method that should sometimes not return a value, you could return an empty Collection, or an Optional, which is new in Java 8.
If you never set a variable to null you can never have an unexpected null.
Don't allow null parameters:
public void method(A param1, B param2, C param3) {
requireNonNull(param1, param2, param3);
...
}
public static void requireNonNull(Object... parameters) {
Stream.of(parameters).forEach(Objects::requireNonNull);
}
Avoid creating "result" variables that are temporarily null:
Instead of:
public Result method() {
Result result = null; // <- this smells
try {
result = ...;
} catch (SomeException e) {
LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
}
return result;
}
you should:
public Result method() {
try {
return ...;
} catch (SomeException e) {
throw new MyPossiblyRuntimeException(e);
}
}
Sooner or later you will start to see usage of null (and mutable variables) as a code smell.
I'm sure you can come up with other smart ways to avoid null, be creative!
tl;dr: NullPointerException should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.
Regarding your comment:
I mean instead of showing a Stack trace error how can we make the user more understandable about the Null pointer that happened.
The user neither knows nor cares about what a Null pointer is. If a NullPointerException occured, it's a bug in your code. It should be caught and logged by the global exception handler, then the bug should be fixed and an update should be shipped.
(You do use a global, catch-all exception handler that logs the exception, apologizes to the user, terminates the application and instructs the user how to send the stack trace to you, right? If not, this might be a good time to start.)