C # 's try-catch-finally exception handling statement

Source: Internet
Author: User
Tags exception handling finally block

When an exception occurs, execution terminates and the control is handed over to the nearest exception-handling statement, which means that it cannot be performed according to the normal design idea. While some resource cleanup, such as closing a file, must always be performed, even if there is an exception, the finally block can be used to implement the feature. Finally blocks are used to clear any resources allocated in a try block and to run the code that must be executed, even in the event of an exception. Control is always passed to the finally block, regardless of how the try block exits.

Use of the example try-catch-finally statement

In this example, there is an invalid conversion statement that causes an exception, and when the program is run, the user receives a run-time error message, but the finally clause continues to execute and the output is displayed. The program code is as follows.

Using System;
public class MainClass
{
static void Main ()
{
int i = 123;
string s = "Some string";
http://www.bianceng.cn
Object o = S;
Try
{
i = (int) o;
}
catch { }
Finally
{
Console.Write ("i = {0}", i);
}
Console.read ();
}
}
Related Article

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.