2012-09-21 59 views
0

我創建了一個名爲ZeroException的繼承的類,它繼承自System.DivideByZero Class,但是當發生分歧的異常時它不捕獲該事件。從system.dividebyzeroexception繼承的異常類

Class ZeroException 
Inherits System.DivideByZero 
Public Overrides ReadOnly Property Message() as String 
Get 
Return "Divide By Zero" 
End Get 
End Property 
End Class 

主要代碼:

Sub Calc() 
dim x as integer=5 
dim y as integer=0 
dim k as single 

Try 
k=x\y 'Integer Division 
Catch ex as ZeroException 
Console.WriteLine(ex.Message) 'But I get another message. Not Divide By Zero 
End Try 

End Sub 
+1

你有這個倒退。你無法捕捉到更多派生的異常。 –

回答

3

你不趕自定義異常,而是你把一個..所以在這種情況下,你的代碼看起來應該如下:

Try 
     k = x \ y 'Integer Division 
    Catch ex As DivideByZeroException 
     Throw New ZeroException 
    End Try 

這裏一個演示這個的測試用例。

Imports System.Text 
Imports Microsoft.VisualStudio.TestTools.UnitTesting 

Class ZeroException 
    Inherits DivideByZeroException 
    Public Overrides ReadOnly Property Message() As String 
     Get 
      Return "Divide By Zero" 
     End Get 
    End Property 
End Class 

<TestClass()> Public Class UnitTest1 

    <TestMethod()> Public Sub TestMethod1() 
     Try 
      MethodThrowsCustomException() 
     Catch ex As Exception 
      Console.WriteLine(ex.Message) 
     End Try 
    End Sub 

    Public Sub MethodThrowsCustomException() 
     Dim x As Integer = 5 
     Dim y As Integer = 0 
     Dim k As Single 

     Try 
      k = x \ y 'Integer Division 
     Catch ex As DivideByZeroException 
      Throw New ZeroException 
     End Try 

    End Sub 

End Class 
+0

好吧,明白了。謝謝 ! –