开发者

Try catch in a final statement?

I am have an asp.net mvc 3 site and when a person edits a task it locks that task so they can edit it and ensure another subscriber does not delete or update the task while they are editing it.

They click edit on the task and it goes and grabs the task and locks it. They edit the task and update.

now I have something like this

public Task Update(Task task)
{
    isLocked = true开发者_运维问答;
    try
    {
        // set task to unlock itself(this is stored on the task row in the db)
        task.locked = false
        task.DateLocked = "6/3/1900";
        task.Commit(); // save the newly updated task; - nhibernate

        isLocked = false;
        return task
    }
    catch(SqlException ex)
    {
        // error logging here
       // "database is down error to user"
    }
    finally
    {
       if(isLocked)
       {
          task.locked = false
          task.DateLocked = "6/3/1900";
          task.Commit();
       }
    }
}

If the task gets updated successfully the file is unlocked so I don't bother doing it again in the finally. If I run into some unexpected error like a null reference(very unlikely as I check for anything that could be null and cause an exception but lets pretend that somehow it happens).

My finally statement would kick in and ensure that the file in unlocked of course the site would blow up and the users would get some generic "something went wrong error" but the file would be unlocked so they could try again.

Now what happens if the error is an SqlException error? It would get caught but the finally statement would still run and it would blow up there as well.

Should I be wrapping the code in my finally block in another try catch?

I do have a scheduled task that runs every so often to ensure that tasks eventually will be unlocked so if it like the database is down it is not like the task is locked for ever it should eventually be unlocked.


From the situation you don't seem to be getting much benifit from running commit statement in finally again. You can do something like this to deal with db only exception like this:

public Task Update(Task task)
{
    isLocked = true;
    try
    {
        //DO OTHER STUFF HERE
    }
    catch(Exception ex)
    {
        // error logging here
    }
    finally
    {
        UpdateToDB(task)
    }
    return task;
}

private Task UpdateToDB(Task task)
{
    try
    {
        task.locked = false
        task.DateLocked = "6/3/1900";
        task.Commit();     
    }
    catch(Exception e)
    {
        //LOG ERROR
    }
    catch(SqlException ex)
    {
       //LOG ERROR
       // "database is down error to user"
    }
    isLocked = false;
    return task
}


Have you considered simply setting a flag to indicate a SQLException being caught and in the finally block, checking for that flag and subsequently taking appropriate action...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜