ibcadmin 发表于 2015-1-3 15:26:15

C#中try catch finally 讲解

try中的程序块是有可能发生错误的程序块,catch中的程序块是当发生错误的时候才会执行的代码块,finally中的程序块是无论是否发生错误都会执行的代码块。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Sample_01_CA

{

    public class Complex

    {

      static void Main(string[] args)

      {

            int i = 2008;

            int j = 0;

            try

            {

                int result = i / j;

            }

            catch

            {

                Console.WriteLine("J变量的值为0");

            }

            finally

            {

                Console.WriteLine(j.ToString());

            }

            Console.Read();

      }

    };

}


程序输出为:

J变量的值为0

0


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Sample_01_CA

{

    public class Complex

    {

      static void Main(string[] args)

      {

            int i = 2008;

            int j = 2;

            try

            {

                int result = i / j;

            }

            catch

            {

                Console.WriteLine("J变量的值为0");

            }

            finally

            {

                Console.WriteLine(j.ToString());

            }

            Console.Read();

      }

    };

}


程序输出为:

2


再说一下,return虽然能跳出整个函数,但是遇到 finally 还是会进 finally的


44378 发表于 2015-1-3 20:46:45

第二段代码输出是2吧?

ibcadmin 发表于 2015-1-4 09:25:45

44378 发表于 2015-1-3 12:46
第二段代码输出是2吧?

谢谢反馈 , 已编辑

881966 发表于 2018-12-4 21:17:37

谢谢分享
页: [1]
查看完整版本: C#中try catch finally 讲解