C#学习笔记六异常

本文通过C#编程实例介绍了异常处理机制,包括如何捕获并打印异常信息,以及如何自定义异常类来处理特定场景的问题。

异常

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace 异常

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                int i = Convert.ToInt32("abc");

            }

            catch (Exception e)

            {

                Console.WriteLine("发生错误:" + e.Message + "\n异常堆栈:" + e.StackTrace);//这样就可以直接打印出发生异常的原因和位置

            }

            Console.ReadKey();

        }

    }

}

 

 

 

namespace 抛出自己的异常

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                string desc = AgeDescribe(300);

            }

            catch(Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        static string AgeDescribe(int age)

        {

            if (age >= 0 && age < 3)

            {

                return "婴儿";

            }

            else if (age >= 3 && age < 18)

            {

                return "青少年";

            }

            else if (age >= 18 && age < 150)

            {

                return "成年人";

            }

            else if (age >= 150)

            {

                throw new Exception("你是神仙吧!");

            }

            else if (age < 0)

            {

                throw new Exception("你来自反物质吧!");

            }

            return "0";

        }

       

    }

}

转载于:https://www.cnblogs.com/tangzhengyue/archive/2011/08/24/2152396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值