Gracefully avoiding NullPointerException in Java

前端 未结 9 1342
夕颜
夕颜 2020-11-30 04:02

Consider this line:

if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....

Obviously this line is a potential bug, the attribute

相关标签:
9条回答
  • 2020-11-30 04:47

    There are certain situations where the concise approach feels wrong to start with but effectively becomes idiomatic. This is one of them; the other is something like:

    String line;
    while ((line = bufferedReader.readLine()) != null) {
      // Use line
    }
    

    Side effects in a condition? Unthinkable! Except it's basically nicer than the alternatives, when you recognise the particular pattern.

    This pattern is similar - it's so common in Java that I'd expect any reasonably experienced developer to recognise it. The result is pleasantly concise. (Amusingly, I sometimes see C# code which uses the same idiom, unnecessarily - the equality operator works fine with strings in C#.)

    Bottom line: use the first version, and become familiar with it.

    0 讨论(0)
  • 2020-11-30 04:54

    I've always used

    if ("true".equals(object.getAttribute("someAttr"))) { // ....
    

    because although it is a little more difficult to read it's much less verbose and I think it's readable enough so you get used to it very easily

    0 讨论(0)
  • 2020-11-30 04:57

    I have another answer;

    List<Map<String, Object>> group = jjDatabase.separateRow(db.Select("SELECT * FROM access_user_group  WHERE user_id=1 ;"));
    

    there is not "group_c80" as column in 'access_user_group' in my database, so in get(0).get("group_c80") null pointer exception accords. But i handled it through below code :

    for (int j = 1; j < 100; j++) {
                        String rulId="0";//defult value,to privent null pointer exeption in group_c
                        try {
                            rulId = group.get(0).get("group_c" + j)).toString();
                        } catch (Exception ex) {
                            ServerLog.Print( "Handeled error in database for " + "group_c" + (j < 10 ? "0" + j : j) +"This error handeled and mot efect in program");
                            rulId = "0";
                        }}
    
    0 讨论(0)
提交回复
热议问题