C#学习笔记<四> 异常与异常处理

m_<:这里记录C#学习的笔记,基础的语法略去,重点在类、方法、继承三项。

1

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int i = Convert.ToInt32("abc");
                Console.WriteLine("123!");   //未执行,出现错误立即执行catch
            }
            catch
            {
                Console.WriteLine("Data error!");
            }
            Console.ReadKey();
        }
    }
}

2

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int i = Convert.ToInt32("abc");
                Console.WriteLine("123!");
            }
            catch(Exception ex)
            {
                Console.WriteLine("Data error: " + ex.Message + "异常堆栈:" + ex.StackTrace);   //定义了Exception类型的ex,Message显示错误,StackTrace显示错误位置 
            }
            Console.ReadKey();
        }
    }
}

3 自己写异常

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                GetAgeDesc(120);
            }
            catch (Exception ex)   //抓到一个异常
            {
                Console.WriteLine(ex.Message);   
            }
            Console.ReadKey();
        }
        static string GetAgeDesc(int age)
        {
            if (age > 0 && age < 120)
            {
                return "human";
            }
            else
            {
                throw new Exception("Error");   //扔出一个异常
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容