目前的理解
,
异常就是程序运行到一个可能会出错的地方
,
并且这个错误正在发生了
,
从而就要求程序处理这个错误
,
异常就是用来处理这个错误的
.
自定义异常
,
就是定义一个类
,
并且可能会要求此类继承系统自定义的某一个类
(
具体语言要求不一样
),
而此类的
BODY
就是几个构造函数
.
具体方法
:
1.
自定义异常类
2.
编写一个可能会产生异常的函数
,
并且在此函数中利用
if
等判断语句来判断在什么条件下抛出异常
,
即
throw
语句
3.
调用
2
中编写的函数
,
放在
try…c
atch…finally
块中
.
具体例子
(
VB.net
编写
)
Public
Class
DevideByZeroException
Inherits
ApplicationException
Public
Sub
New
()
Console.WriteLine("DevideByZeroException"
)
End
Sub
End
Class
Module
Module1
Sub
Main()
Dim
dividend As
Single
Dim
divisor As
Single
Dim
quotient As
Single
Console.WriteLine("Please input two
numbers:"
)
Console.Write("the dividend:"
)
dividend =
Convert.ToSingle(Console.ReadLine())
Console.Write("the divisor:"
)
divisor = Convert.ToSingle(Console.ReadLine())
Try
quotient =
Devide(dividend, divisor)
Catch
ex As
DevideByZeroException
Console.WriteLine()
GoTo
jump
Finally
End
Try
Console.WriteLine(quotient.ToString())
jump:
Console.ReadLine()
End
Sub
Public
Function
Devide(ByVal
dividend As
Single
, ByVal
divisor As
Single
)
As
Single
If
(Math.Abs(divisor) < 0.000001) Then
Throw
New
DevideByZeroException()
End
If
Return
dividend / divisor
End
Function
End
Module
在
VB.NET
中
,
所在自定义异常要求继承自
ApplicationException
类
.
--------------------------------------------------------------------------------------------------------------------------
于2008年4月9日