第二节 12异常 简单

using System;
/* 异常异常处理
 * 传统的错误表达方式: 错误码,举列
 * 错误码的缺点:不处理的则很难发现,每次处理则很麻烦,难以看出错误的原因,容易使得程序进入不确定的状态
 * try catch Exception ex异常也是对像
 * Exception类主要属性: Message, StackTrace
 * 发生异常后程序默认就退出了,后续代码不会被执行了,catch以后的代码则会继承执行
 * 不要吃掉异常
 * 扔出自己的异常
 *
 */
namespace _12异常
{
    class Program
    {
        static void Main(string[] args)
        {
            /*int i = DeleteFile(@"c:/avi");
            Console.WriteLine("删除结果:{0}",i);
            try {
                Console.WriteLine("Convert之前");
                int ii = Convert.ToInt32("aaaa");
                Console.WriteLine("Convert之后");
            }catch(Exception ex){
                Console.WriteLine("类型错误:"+ex.Message+". 异常堆栈:"+ex.StackTrace);
            }
            Console.WriteLine("ReadKey之前");*/
            try
            {
                string desc = GetAgeDesc(400);
            }
            catch (Exception ex) {
                Console.WriteLine("数据错误:{0}",ex.Message);
            }



            Console.ReadKey();
        }

        static int DeleteFile(string filepath) 
        {
            //尝试删除文件,发现无法删除
            return -1;
            //return 0如果没有权限, return -2,找不到要删除的文件
        }

        static string GetAgeDesc(int age) 
        {
            if (age >= 0 && age <= 3) {
                return "婴幼儿";
            }
            else if (age >= 3 && age <= 18) 
            {
                return "少年";
            }
            else if (age >= 18 && age <= 180)
            {
                return "成年人";
            }
            else if(age < 0) {
                throw new Exception("您来自反物质世界吧1");
            }else{
                throw new Exception("您见过老佛爷吧!");
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/xiangxiaodong/p/2367473.html