Pergunta

I have a layout that when I try to make a specific kind of query to MySQL (insert, update or select)

Method()
{
    Connect();

    if ( i == 1)
    {
        try 
        {
            // Query Db...
        }
        catch {}
        finally 
        {
            // Close Connection.
        }
    }
    else if ( i == 2)
    {
        // More try/catch...
    }
}

However i was wondering if this way was better?

Method()
{
    Connect();
    try
    {
        if ( i == 1)
        {
            // Query Db...
        }
        else if (i == 2)
        {
            // Query Db...
        }
    }
    catch { }
    finally
    {
        // Close Connection
    }
}

Is there any real difference or benefit to one or another?

Foi útil?

Solução

Second one is better, since you have if / else if statements, only one of them will be executed, and might throw an exception.So, putting the statement into a try/catch is more logical.In this case I can't see any advantage of using first version over to second.Your second code snippet does the same job with less code.

However, if you want to handle different exceptions on each statement then you will have to use different try / catch statements.

Outras dicas

The second approach is better.

If you are going to use several if / else if, it'd be a nice idea to isolate the code that will be in the part // Query db inside a method so you don't have to repeat your code. Then you can pass your queries a parameter of this method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top