C# 自定义异常类 throw语句抛出异常

Exception概述:

异常(Exception)一般分为两大类SystemException、ApplicationException,前者是预定义的异常类,后者是用户自定义异常类时需要继承的类

简单自定义异常类Demo

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

namespace finallyReturn
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入1~4的数");

            try
            {
                int num = int.Parse(Console.ReadLine());
                if (num < 1 || num > 4)
                    throw new MyException("数不在范围内");
            }
            catch (MyException me)
            {
                Console.WriteLine(me.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);                
            }
            finally
            {
                Console.WriteLine("我在Finally中");
            }

            Console.ReadLine();
            return;
        }
    }

    class MyException : ApplicationException
    { 
        //public MyException(){}
        public MyException(string message) : base(message) { }

        public override string Message
        {
            get
            {
                return base.Message;
            }
        }
    }
}

这里面自定义了异常类MyException:ApplicationException,catch(MyException me)用户捕获自定义异常,catch(Exception e)用于捕获一般异常,如果异常被第一个catch捕获,那么第二个catch将不会执行,直接执行finally中的语句。

原文地址:https://www.cnblogs.com/xiangyangzhu/p/4239792.html