Hey
I have a web service. Normally my web services do som DB things and then
returns a return class that i have made, but sometimes i need functions. I
use a try/catch in the first function to catch all errors, but then i cant
close the DB connections.
Consider this:
[WebMethod]
private retClass firstfunc()
{
retClass ret = null
try
{
ret = new retClass();
if (SecondFunc())
ThirdFunc();
}
catch
{
retClass.err = 1;
}
finally
{
//Really great if i could just close the DB connections here
}
}
private bool SecondFunc()
{
//All kinds of things happens here, but most important is the Connection
to the database
...
...
Conn.Open();
...
Conn.Close();
return true;
}
private void ThirdFunc()
{
//All kinds of things happens here, but most important is the Connection
to the database
...
...
Conn.Open();
...
Conn.Close();
}
Well, i could open my connection in FirstFunc(), but i would consider this
bad programming practice.
I could also just do a try/catch inside SecondFunc() and ThirdFunc(). I
guess this would give a little overhead, but you could live with that.
So whats the problem here? The problem is that if i catch the error in
SecondFunc() it will go straight to the catch/finally of SecondFunc(). Then
it will return to FirstFunc() as if nothing had happened, and the return
class for my WebService would give the main application an idea of
"everythings fine", even though it isnt.
Now i have a solution for this, wich is to just make retClass object in
SecondFunc(), and the return that to FirstFunc() like this:
[WebMethod]
private retClass firstfunc()
{
retClass ret = null
try
{
ret = new retClass();
ret = SecondFunc()
if (ret.err = 0 &&)
ThirdFunc();
}
catch
{
ret.err = 1;
}
finally
{
//Really great if i could just close the DB connections here
}
return ret;
}
private retClass SecondFunc()
{
retClass ret = null
try
{
ret = new retClass();
//All kinds of things happens here, but most important is the
Connection to the database
...
...
Conn.Open();
...
Conn.Close();
}
catch
{
ret.err = 1;
}
finally
{
Conn.Close(); //This is an example. I know that there might not be
anything to close in this example wich will also generate an error.
}
ret.boolVal = true;
return ret;
}
private void ThirdFunc()
{
//All kinds of things happens here, but most important is the Connection
to the database
...
...
Conn.Open();
...
Conn.Close();
}
I would like to hear if anyone knows of a better way of doing this. I would
of course like to have my connections closed, but at the same time i would
like to get rid of the complexity of this second scenario???
Or am i doing things the way it should be done in the second scenario?
--
Jimmy
|