Java Exception Handling - Style

后端 未结 8 1645
别跟我提以往
别跟我提以往 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: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!)

提交回复
热议问题