Java Exception Handling - Style

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

    I always do mine the second way, because it allows for me to set cursor as final. There's no reason I can see to have the assignment in the try clause if you are not actually trying to catch exceptions from it.

    EDIT: Just to note, from the further discussion that has gone on. This is how I would handle the openCursor call throwing an exception:

    try
    {
        // ALLOCATE RESOURCE
        final Cursor cursor = db.openCursor(null, null);
    
        try
        {
            // USE RESOURCE
        }
        finally
        {
            // DISPOSE RESOURCE
            cursor.close();
        }
    }
    catch(OpenCursorException e)
    {
        // Handle this appropriately.
    }
    

    Note the clean separation of allocation, usage, and disposal. The only time this gets a little interesting is if the usage try block throws the same exception that you're catching for the allocation try block. (IOException would be a particularly good example of this, as opening and reading can both throw one.) In that case, everything will still clean and dispose correctly, but you might incorrectly attribute failure to an initialization exception instead of a usage exception. In this case, you will want to catch the exception(s) in the inner try block and handle them immediately in there.

提交回复
热议问题