异常_try_catch_finally(杂类演示)

异常_try_catch_finally(杂类演示)<19/9/2017>

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

namespace TryCatchFinally
{
    class Program
    {
        static void Main(string[] args)
        {
            Bank bank = new Bank(24000);
            while (bank.Money > 0)
            {
                Console.WriteLine("请输入取款金额:");
                int tk = int.Parse(Console.ReadLine());
                try
                {
                    bank.Withdrawal(tk);
                }
                catch
                {
                    Console.WriteLine("余额不足");
                }
            }
        }

        public static int Div(int a, int b)
        {
            try
            {
                return a / b;
            }
            catch (DivideByZeroException e0)
            {
                Console.WriteLine(e0);
                return 0;
            }
            catch (NullReferenceException e1)
            {
                Console.WriteLine(e1);
            }
            catch (Exception)//如果异常Exception有交集,把范围大的放下面
            {
                throw new Exception("自定义异常");
            }
            finally//无论是否异常我都会被打印,即使try里面有return
            {
                throw new Exception("瞎搞");
            }
        }

        public static int Sum(int a, int b)
        {
            if (a > 256 || b > 256)
            {
                throw new MyException("该结果超出了规定范围");
            }
            return a + b;
        }

        public class Bank
        {
            public int Money;
            string messageTakeMoney = "";
            int count = 0;
            public Bank(int money)
            {
                this.Money = money;
            }
            public void Withdrawal(int money)
            {
                if (money > Money)
                {
                    throw new MyException("您的余额不够,余额还剩:" + Money + "\n" + messageTakeMoney);
                }
                this.Money -= money;//一定要加this
                messageTakeMoney += "第" + (++count) + "次取了" + money + "元,余额还有" + Money + "元" + "\n";
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值