自定义异常类?
自定义异常类可以帮助开发人员快速定位到你的错误地址
比如你有个人类,该类有个自我介绍函数实现输出自己的基本信息,但该类要接受一个整数参数来表示自己的年龄。
但是有些人在调用该方法的时候一不小心把该参数写错成-10了,从代码的角度来说这个没错,因为整数可以包含负数,但是从逻辑上来讲就不行了,人哪里有负年龄的?所以你就要抛出一个异常来告诉人家你这个地方错了,但是你要怎么告诉它呢?你就自己定义自己的异常类就OK了!
可懂?
使用自定义异常可以根据实际情况执行特定的程序。
throw 用来抛出异常,可自己编写代码,抛出所需要的异常。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckedAndUnchecked
{
class Program
{
static void Main(string[] args)
{
int month;
string b;
Console.WriteLine("请输入月份的值:");
b = Console.ReadLine();
month = int.Parse(b);
switch (month)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("Feburary");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("Novemer");
break;
case 12:
Console.WriteLine("December");
break;
default:
throw new ArgumentOutOfRangeException("不存在的月份"); // throw
}
}
}
}
如果.net 中自带的异常能满足要求那也没有必要使用自定义异常。
比如只需要表示出现了一个异常,然后带有错误描述,一般使用ApplicationException就行了
要表示发生了一个windows 错误,并需要附带错误代码,那使用Win32Exception就足够了
但是有某些情况下已有的异常无法满足你的要求时就需要使用自定义异常了。比如你希望异常对象中带有特别的属性或是函数来帮助描述这个异常,那你一定要使用自定义异常了。。
不然就直接把你程序崩掉了
你是说的try么