About try... Use of catch... finally

Source: Internet
Author: User
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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.