We all like to use try provided by Ms... catch... finally, this is indeed a good news for C # developers. In the past, Delphi developers often use try... finally .. end, try .. else t .. end achieves the same effect. However, in some cases, the usage is indeed different. Let's look at an example:
Broker = New Broker ();
Try
{
Broker. open ();
//Processing and judgment Logic
//End
Broker. begintrans ();
//Transaction Processing
//End
Broker. committrans ();
}
Catch (Exception ex)
{
Broker. rollbacktrans ();
ThrowEx;
}
Finally
{
Broker. Close ();
}
If an exception occurs in the judgment logic, it is clear that the broker needs roolback in the catch. At this time, there is a problem. How can the broker roll back without starting trans. So it should be changed to the following: Broker = New Broker ();
Try
{
Broker. open ();
// Processing and judgment Logic
// End
Try
{
Broker. begintrans ();
//Transaction Processing
//End
Broker. committrans ();
}
Catch (Exception ex)
{
Broker. rollbacktrans ();
ThrowEx;
}
}
Finally
{
Broker. Close ();
}
An exception in the judgment logic is handled in the catch that calls this method. Of course, you can catch the exception yourself. This is equivalent to processing in Delphi.
Try
Conn. open ();
// Processing logic
Try
Conn. begintrans ();
// Process the transaction
Conn. committrans ();
Exception
Conn. rollbacktrans ();
End
Finally
Conn. Close ();
End