异常_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";
}
}
}
}