Java Exception Handling - Style

后端 未结 8 1639
别跟我提以往
别跟我提以往 2021-01-17 15:42

Historically I have always written my Exception handling code like this:

    Cursor cursor = null;
    try {
        cursor = db.openCursor(null, null);
             


        
相关标签:
8条回答
  • 2021-01-17 16:12

    No, you finally got it right.

    Don't assign dummy values (null, in this case) to suppress compiler warnings about the use of uninitialized variables. Instead, heed the warning, and initialize your variables properly—as your second, "lazy" example demonstrates.

    0 讨论(0)
  • 2021-01-17 16:14

    If the openCursor() method doesn't throw an exception, the latter is fine. If it does, then you would definitely want to use the former. The reason being that any exception would be thrown to the caller. If the calling method isn't set up to handle that then there is an issue.

    0 讨论(0)
  • 2021-01-17 16:21

    Different people have different opinions.But It is recommended to use first option because if there is any trouble opening the cursor, an exception could be thrown and handled.That is one safe way of programming.

    0 讨论(0)
  • 2021-01-17 16:28

    There is really nothing wrong in doing :

    Cursor cursor = db.openCursor(null, null);  
      try {  
         // do stuff  
       } finally {  
          try {  
            cursor.close();  
         } catch( SomeOther so ){}  
     }  
    
    0 讨论(0)
  • 2021-01-17 16:29

    The second style is fine as long as neither of the method arguments is a calculated expression that can throw its own exception and needs cleaning up after.

    0 讨论(0)
  • 2021-01-17 16:33

    (Update: the question was corrected based on this answer, so the first part of this answer no longer makes sense.)

    The first example is wrong. It will throw a NullPointerException if db.openCursor fails. The second is better.

    By the way, I often see the first method done like this:

    Cursor cursor = null;
    try {
        cursor = db.openCursor(null, null);
        // do stuff
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    

    It isn't more safe doing this that doing it your second way though, but it is often used in examples and I've seen it used a lot in real code.

    One reason why the second method is better is that a bug in the code in the // do stuff section can set the Cursor to null, causing the cursor to not be closed and creating a leak. All in all I can see no good reasons to use the first method (even when it is corrected with the null check), and reasons to avoid using it. Stick to the second method.

    (Thanks to PSpeed for the useful comments!)

    0 讨论(0)
提交回复
热议问题