我有大约20个可能的异常消息,我想在发生错误时抛出。 在捕捉异常时我需要像这样的somthng
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的类答案 0 :(得分:2)
不,您不需要将每个异常类直接从Exception
继承。但您需要确保所有您自定义异常可以通过父层次结构从Exception
派生。例如,请参阅以下继承树:
Exception | |-MyGenericException | |-MyFooException | |-MyBarException | |-OtherGenericException |-OtherFooException |-OtherBarException
请注意,某些异常类不直接从Exception
继承,但是它们有一个父类,它是从Exception
派生的。
示例代码是在C#中用记事本写的,但希望你能得到这个想法。
另外2个常规异常类继承自Exception
。它们是MyIOException
和MySecurityException
。其他四个较不通用的类派生于它们。
//------------ 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;}
}