自定义异常

目前的理解 , 异常就是程序运行到一个可能会出错的地方 , 并且这个错误正在发生了 , 从而就要求程序处理这个错误 , 异常就是用来处理这个错误的 .

 

自定义异常 , 就是定义一个类 , 并且可能会要求此类继承系统自定义的某一个类 ( 具体语言要求不一样 ), 而此类的 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日

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值