小知识点:Try_Catch

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DemoTryCatch
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TestThrow();
            }
            catch
            {
 
            }
        }

        public static int test1()
        {
            int i = 1;
            try
            {
                return ++i;
                throw new Exception("dfsdfsf");
            }
            catch (Exception ex)
            {
                string str = ex.StackTrace;
                return i++;
                //throw new Exception("dfsdfsf");
            }
            finally
            {
                ++i;
                Console.WriteLine("finally:" + i);
            }
        }

        public static int test2()
        {
            int i = 1;
            try
            {
                throw new Exception();
            }
            catch (Exception ex)
            {
                return ++i;
            }
            finally
            {
                ++i;
                Console.WriteLine("finally:" + i);
            }
        }

        //public static int test3()
        //{
        //    try { }
        //    finally
        //    {
        //        return 1;
        //    }
        //}

        ///1.不管出没出现异常,finally块中的语句都会执行;
        //2.当try或catch块中有return语句时,finally块中的语句仍会执行;
        //3.finally块中的语句是在函数返回前执行的,但函数返回值是在finally块中语句执行前确定的;
        //4.finally块中不能包含return语句。
        //5,(如果该函数要求有返回值)try中也必须要有能够返回函数的调用,比如return ,或者throw excetion(),
        //                      而且cath中也必须要有能够返回函数的调用,比如return ,或者throw excetion()。
        //(相反如果该函数没有返回值,try和cath中的对能够返回函数的调用时不需要的)

 

        class CustomException : Exception
        {
            public CustomException(string message)
            {

            }
        }

        private static int TestThrow()
        {
            CustomException ex =
                new CustomException("Custom exception in TestThrow()");
            return 10;
            throw ex;
        }
        //6.这种情况是不会去抓异常的,有点变态。

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值