2014-01-30 60 views
0

我有一个继承Exception的自定义异常类。 在我的Try-Catch块中,有一行代码会导致InvalidCastException。未捕获但未处理的自定义异常

但是,异常总是在导致它的代码行上未处理,并且未被Catch块捕获。

Public Class InvalidPremiumException 
Inherits System.Exception 

Public Sub New() 

End Sub 

Public Sub New(message As String) 
    MyBase.New(message) 
End Sub 

Public Sub New(message As String, inner As Exception) 
    MyBase.New(message, inner) 
End Sub 

End Class 

然后在另一个类:

Try 
' code that causes an InvalidCastException here 

Catch ex As InvalidPremiumException 
Console.WriteLine("Invalid or Missing Premium") 
End Try 
+0

如果我的答案已经解决了您的问题,请将其标记为'答案' –

回答

0

您在Catch块醒目InvalidPremiumException。只有该例外将被捕获到类型为InvalidPremiumException的块中,或者从该块中继承,其他块将不受处理。

您也可以考虑使用多个catch块。

InvalidCastException将在第二Catch块进行处理:

Try 
    ' code that causes an InvalidCastException here 

Catch ex As InvalidPremiumException 
    Console.WriteLine("Invalid or Missing Premium") 

Catch ex As Exception 
    Console.WriteLine("Catching other exceptions") 
End Try 

Catch块将只处理那些是相同类型或其子女类型的一个例外。这就是为什么您的自定义异常在第二个块中处理的原因。

+1

那么自定义例外中的重点是什么? – user3231512

+0

如果我正确理解问题,告诉我。你想在处理InvalidPremiumException的Catch块中捕获InvalidCastException? –

+0

啊 - 我没有时钟的评论说'InvalidCastException' - @ user3231512是这个实际的代码,这是导致问题? – doctorlove

相关问题