c#异常处理

模拟银行应用系统中的存钱和取钱功能,定义一个异常类完成当用户取钱额大于存折余额时进行异常处理,并给用户一个友好的提示。

这里写图片描述

copyright vivi_and_qiao liwei
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class withdrawexcept : Exception
    {
        public void show()
        {
            Console.WriteLine("您的账户余额没有这么多钱!程序已经终止");
        }
    }
    class Account
    {
        double money;
        public Account(double m)
        {
            money = m;
        }
        public void setmoney(double m)
        {
            money = m;
        }
        public void withdraw()
        {
            double withdraw;
            Console.WriteLine("请输入取款金额!");
            withdraw = double.Parse(Console.ReadLine());
            if (withdraw > money)
                throw new withdrawexcept();
            else
                money -= withdraw;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            Account account=new Account(100);
            try
            {
                account.withdraw();
            }
            catch(withdrawexcept e)
            {
                e.show();
            }
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(c#语言程序设计)