开发者

check for null before dereferencing or just catch the null reference thru exception

check for null before deferencing or just catch the null reference thru exception? pro and cons?

for th开发者_开发知识库e 2nd option, it gives clean and sometimes better performed code. for the 1st option, it may give you the nonstop flow that you wanted


I'd say it depends completely on the situation. There is nothing wrong with throwing an exception if the are just that: exceptions.

On the other hand, if you expect that a null value can appear at the given point (without there being an underlying error) then for sure you should check for null before using/deferencing the object.

But again, I don't think that there is an absolute right or wrong here - it depends on the situation.


The article C++ Exceptions: Pros and Cons goes further into pros and cons with exceptions. Its for C++ but I suppose that the logic can be transferred to many other of flavors of programming languages as well. They're conclusion starts with: "There is no simple answer to the "exceptions or error codes" question. The decision needs to be made based on a specific situation that a development team faces. Some rough guidelines may be: ..."


Check for null. Depending on the system's exception handling system is sloppy, and exceptions may have resource allocation needs that can cause issues (rare, but possible).


Check for null at system boundaries and handle it appropriately. Within your software, you know when something should be able to be null and what that means, so there's no reason to make unnecessary checks or catch exceptions that will never be thrown. Test your code where it interfaces with other components to be sure that it handles, for instance, nulls returned by third-party code or passed in by callers of your public API.

IMO, you should almost never have to catch NullPointerException/NullReferenceException (or whatever your language calls it). If a third-party library returns null, the best way to handle it is usually to throw your own exception, with a clear message that you can later log or bubble up to the user, e.g.:

if(returnedValue == null)
{
    throw new MyDescriptivelyNamedException("libcrappy returned null again!");
}

If a consumer of your component passes in a null argument, throw an ArugmentNullException, IllegalArgumentException, or whatever is appropriate for your language/application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜