Is it a acceptable approach to put try catch wherever null pointer exception occurs?

There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

1

If you’re using third party code that is returning null, it’s much better to check the return value.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
...
}
</code>
<code>ThirdPartyValue thirdPartyValue = thirdParty.getValue(); if (null == thirdPartyValue) { ... } </code>
ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
    ...
}

Edit: Java 8 is out! This should now be

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());
</code>
<code>Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue()); </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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);
}
</code>
<code>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); } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public Result method() {
Result result = null; // <- this smells
try {
result = ...;
} catch (SomeException e) {
LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
}
return result;
}
</code>
<code>public Result method() { Result result = null; // <- this smells try { result = ...; } catch (SomeException e) { LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e); } return result; } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public Result method() {
try {
return ...;
} catch (SomeException e) {
throw new MyPossiblyRuntimeException(e);
}
}
</code>
<code>public Result method() { try { return ...; } catch (SomeException e) { throw new MyPossiblyRuntimeException(e); } } </code>
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.

1

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.)

2

It depends on the code block, but yes, in many cases try-catch is a good solution to handle a number of null-pointer related bugs you are not prepared to address individually. You need to fulfill two conditions to make exceptions useful:

  1. Non-locality of handling: Don’t use try-except when a simple if would suffice. Use try-except when the error occurs far from the place where it is handled, e.g. deep in the call stack or within a large block of code.
  2. Useful error handling: Do more than the default exception handler. Logically abort an operation with a useful error message. Handle the exception at a point where you can actually make an informed decision over the high-level process. In a MVC GUI application, the Controller is often a good place. Under no circumstances handle the exception close to the generating point, log it and forget about it – that’s just useful for your logs.

4

No. If someone passes a null pointer where you did not expect it, then that’s a bug. Make them deal with the exception- it’s their problem.

3

There’s no point in placing exception handling where you aren’t really handling exceptions. It’s a lot of extra code & makes following the program difficult. If you want to show ‘friendly’ errors to users, just have a top-level exception handler.

Using a try-catch block every time will make your code needlessly complicated and less readable. Besides, if your code is thought thoroughly, there usually shouldn’t “unpredictable” null pointers.

In most cases a simple check if some variable is null is enough. If necessary, you could log a message if a variable is null.

The real answer is that it depends on the domain of the application.

Is it more important that it functions exactly to spec (Financial Hedging calculator giving wrong results) or is it more important that it stays up no matter what (e-commerce site with a fudged up header)?

In some business a slightly-wrong result is worse than no result at all. In those cases you want to fail fast loud and explicit when something unexpected and strange happens so that people who inspect the logs can do their work and the root cause can be found and fixed.

Meanwhile if that is not your situation, and the goal is maximum uptime then thiton’s answer is the way to go.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

This sounds like the anti-pattern of using exceptions for control flow (specifically, null pointer exceptions).

So, no, it is not good programming practice to do this. When possible, your code should avoid raising a null pointer exception, and use break/return for control flow instead.

The only exception is when interfacing with a library that non-deterministially raises a null pointer exception to signal a certain type of error. In this case, the library is an example of the anti-pattern, and the only thing you can do is catch the exception, of course.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật