Try/catch/finally

Source: Internet
Author: User
Tags sql error

Example:

Code 1 public void ExecuteSql (string conString, string region string)
2 {
3
4 SqlConnection con = new SqlConnection (conString );
5
6 try
7
8 {
9
10 con. Open ();
11
12 SqlTransaction tran = con. BeginTransaction ();
13
14 SqlCommand cmd = new SqlCommand (character string, con );
15
16 try
17
18 {
19
20 cmd. ExecuteNonQuery ();
21
22 tran. Commit ();
23
24}
25
26 catch (SqlException ex)
27
28 {
29
30 Console. WriteLine (ex. Message );
31
32 // implement transaction rollback
33
34 tran. Rollback ();
35
36 throw new Exception ("SQL Error! ", Ex );
37
38}
39
40}
41
42 catch (Exception e)
43
44 {
45
46 throw (e );
47
48}
49
50 finally // no matter whether an exception is thrown or not, the program will execute finally and generally process the release of resources.
51
52 {
53
54 con. Close ();
55
56}
57}

 

 

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.