Exception handling 未捕获自定义异常,但未处理

Exception handling 未捕获自定义异常,但未处理,exception-handling,try-catch,Exception Handling,Try Catch,我有一个继承异常的自定义异常类。 在我的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

我有一个继承异常的自定义异常类。 在我的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

您正在
Catch
块中捕获
InvalidPremiumException
。只有类型为
InvalidPremiumException
或从中继承的异常才会在该块中被捕获,其他异常将不被处理

您也可以考虑使用多个<代码> catch <代码>块。< /p>
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
块将只处理相同类型或其子类型之一的异常。这就是在第二个块中处理自定义异常的原因。

告诉我是否正确理解该问题。你想在处理InvalidPremiumException的catch块中捕获InvalidCastException吗?啊-我没有记下评论说的
InvalidCastException
-@user3231512这是导致问题的实际代码吗?我想知道的是,为什么你不能捕获异常(定义为从异常派生的自定义异常),在Catch块中,您可以这样做,但是(正如我已经提到的)它必须是同一个类或继承自它的类。另一个选项可以是添加多个catch块。我正在使用从它继承的一个!我正在使用InvalidPremiumException继承Exception。现在,Exception是一个通用类,所以如果我说:catch InvalidPremiumExceptionI,我应该能够捕获所有和任何特定的异常如果我下面的答案解决了您的问题,请将其标记为“答案”