您的位置:首页 > 职场人生

黑马程序员_学习日记25_异常

2012-06-03 22:01 351 查看
1、 公共异常类

System.ArithmeticException
在算术运算期间发生的异常

System.ArrayTypeMismatchException
当存储一个数组时,如果由于被存储的元素的实际类型与数组的实际类型不兼容而导致存储失败,就会引发此异常。

System.DivideByZeroException
在试图用零除整数值时引发

System.IndexOutOfRangeException
在试图使用小于零或超出数组界限的下标索引数组时引发

System.InvalidCastException
当从基类型或接口到派生类型的显示转换在运行时失败,就会引发此异常

System.NullReferenceException
在需要使用引用对象的场合,如果使用null引用,就会引发此异常

System.OutOfMemoryException
在分配内存的尝试失败时引发

System.OverflowException
在选中的上下文中所进行的算术运算、类型转换或转换操作导致溢出时引发的异常

2、 throw语句

throw语句用于主动引发一个异常,使用throw语句可在特定情形下,自动抛出异常。例:

class Program

{

class test

{

public int MyInt(string a, string b)

{

int int1;

int int2;

int num;

try

{

int1 = int.Parse(a);

int2 = int.Parse(b);

if (int2 == 0)

{

throw newDivideByZeroException();

}

num = int1 / int2;

return num;

}

catch (DivideByZeroExceptionde)

{

Console.WriteLine("用零整除引发异常!");

Console.WriteLine(de.Message);

return 0;

}

}

}

static void Main(string[] args)

{

try

{

Console.WriteLine("请输入分子:");

string str1 =Console.ReadLine();

Console.WriteLine("请输入分母:");

string str2 =Console.ReadLine();

test tt = new test();

//调用test类中的MyInt方法,获取键盘输入的分子与分母相除得到的值

Console.WriteLine("分子除以分母的值:" + tt.MyInt(str1,str2));

}

catch (FormatException)

{

Console.WriteLine("请输入数值格式数据");

}

Console.ReadLine();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: