1

当发生错误时,我想抛出大约 20 条可能的异常消息。捕捉异常时我需要这样的东西

Try
    ' do domthing
Catch ex As CustomInvalidArgumentException
     'do domthing
Catch ex As CustomUnexcpectedException
     'do domthing
Catch ex As Exception
     'do domthing
End Try

目前我有这样的课

<Serializable()> _
Public Class CustomException
    Inherits Exception

    Public Sub New()
        MyBase.New()
    End Sub

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

    Public Sub New(ByVal format As String, ByVal ParamArray args As Object())
        MyBase.New(String.Format(format, args))
    End Sub

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

    Public Sub New(ByVal format As String, ByVal innerException As Exception, ByVal ParamArray args As Object())
        MyBase.New(String.Format(format, args), innerException)
    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.New(info, context)
    End Sub
End Class

我是否必须为每种类型的异常创建一个从 Exception 继承的类

4

1 回答 1

2

不,您不需要让每个异常类直接继承自Exception. 但是您需要确保所有自定义异常都可以Exception通过父层次结构派生。例如,请参阅以下继承树:

例外
|
|-MyGenericException
| |-MyFooException
| |-MyBarException
|
|-其他通用异常  
   |-OtherFooException
   |-OtherBarException

看,一些异常类不直接ExceptionException.

示例代码是用记事本编写的 C# 代码,但希望您能明白这一点。

2 个更通用的异常类继承自Exception. 它们是MyIOExceptionMySecurityException。其他四个较不通用的类派生自它们。

//------------ Networking
public class MyIOException : Exception
{
    public string AdditionalData {get; set;}
}
public class MyNetworkFailureIOException : MyIOException
{
    public string Reason {get; set;}
}
public class MyRemoteFileNotFoundIOException : MyIOException
{
    public string RemotePath {get; set;}
}

//------------ Security
public class MySecurityException : Exception
{
    public string UserName {get; set;}
}
public class MyAccessDeniedException : MySecurityException
{
    public string PolicyName {get; set;}
}
public class MyUnauthorizedException : MySecurityException
{
    public string CodeName {get; set;}
}
于 2012-06-19T11:16:11.767 回答