Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with null pointers

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to deal with null pointers". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to deal with null pointers".

NullPointerException

The title is eye-catching, in order to tell you that this null pointer is abnormal, to be honest, many of them can be easily solved in the project, but sometimes the cause of the problem is that you can never think of it, and it looks like this.

The front-end code is as follows:

Var setting = {url: "findFileById", data: {id:id}, success:function (data) {console.log (data) }, error:function (data) {console.log ("query file exception")}} ajax (setting) Here, ajax just encapsulates function ajax (setting) {$.ajax ({type: "post", url:setting.url+ ".do", dataType:setting.dataType | | "json", contentType: "application/json"). Utf-8 ", data:JSON.stringify (setting.data) | | {}, async:setting.async, success:function (data) {setting.success (data);}, error:function (data) {setting.error (" API error, try again ");}})

The backend business is processed as follows:

PostMapping ("findFileById") @ ResponseBody public File findFileById (HttpServletRequest request, HttpServletResponse response, @ RequestBody Map map) {return deliverFileService.findFileById (request,map);}

People will certainly say that you can't do such a simple thing. There is something wrong with a query file. In fact, my colleague did not fully deal with the problem of null value in the code. As a result, there has been a "interface error, please try again" error in ajax.

The problem is that he did not deal with empty data, but directly returned to me, this question is also very strange, most of the time should not deal with empty data in order to prevent NULL exceptions? And A Fan immediately found him, he said no problem, normal call in him, I was embarrassed at that time, the parameters I passed to you is no problem, if the query data is empty, there should be a prompt. So A Fan can only simply modify his code and become

PostMapping ("findFileById") @ ResponseBody public File findFileById (HttpServletRequest request, HttpServletResponse response, @ RequestBody Map map) {return deliverFileService.findFileById (request,map)! = null? deliverFileService.findFileById (request,map): new; new DeliverFile ();}

Ah Fan can't change him too much. I can only change it to null. If it's an empty object, just return me an empty object. If not, return the query data to me completely.

So, Ah Fan, let's talk about how to deal with our null value now. Otherwise, if you write the data interface and call it to someone else, it will be fine if it is an empty string, but if it is something like null, it will certainly be despised to death by others.

How to deal with null pointer exception

When will NullPointerException appear?

We all know that NullPointerException inherits RuntimeException, that is, the exception information that will occur at run time. When we write code, if the code is running, when the object we use is not initialized, or when it is empty, there will be a null pointer exception, and this exception is also the most Low that we feel, the least likely exception, but often because of our own inattention, it occurs.

In fact, there are too many ways, and most of the time we don't pay attention to this thing, such as object, null operation, but if you check null when each object is used, then your code will really appear:

If (invalid null) {if (bounded null) {if (cased empty null) {.... }}}

When you see this kind of code, the first feeling is not directly want to pull this friend over to beat, this kind of writing too much, people are going crazy, especially the secondary maintenance personnel.

In fact, although this method is stupid, it is also a habit of judging emptiness. Functionally, it will certainly not cause much trouble, but such a null value is also very excruciating, so let's deal with it.

1. Let's not talk about this and directly judge whether the object is empty or not.

The second is that when comparing equals methods, we often have this kind of writing habit.

If (text.equals ("xxxxx")) {}

In fact, there is no problem with such a comparison, but have you ever thought that if your text is empty? Didn't you make a mistake when you compared it? An interviewer once asked me why writing a known string in front of a written question might just be a habit at that time, but it turned out to be really useful.

You change it to:

If ("xxxxx" .equals (text)) {}

Will avoid the error of null pointer, what a good habit, isn't it?

The third is the feature Optional that we provide in Java8.

OfNullable, which is provided in Optional, passes the parameters we need to determine whether it is empty or not.

For collections, you can use the modified method to determine whether it is null. If it is null, we must return even an empty object or an empty collection, which is very friendly to people who call your API later.

I know that many people will say, then I will write a comment on the interface, the value returned by the query may be empty, everyone be careful to call, although you prompt the problem, but you do not solve the problem, it is equivalent to, you threw out all the exceptions without dealing with him.

At this time, we can also use the Optional provided in Java8, such as this.

OptionalgetProductOptional (String id)

At this time, when our caller knows that there is an Optional, it naturally understands.

Thank you for your reading, the above is the content of "how to deal with null pointers", after the study of this article, I believe you have a deeper understanding of how to deal with null pointers, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report