• 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中的语句。

  • 相关阅读:
    Git 创建仓库并拉取代码
    Linux export 命令
    Linux ps 命令
    Linux sed 命令
    Linux find 命令
    Linux chmod 命令
    Linux chgrp 命令
    解除/配置 linux/nginx 的 tcp 连接(nginx配置文件日常配置推荐)
    更改Ubuntu的apt源
    anaconda 各版本的下载地址
  • 原文地址:https://www.cnblogs.com/xiangyangzhu/p/4239792.html
Copyright © 2020-2023  润新知