gpt4 book ai didi

.net - 使用自定义异常类抛出多个异常

转载 作者:行者123 更新时间:2023-12-03 07:51:01 25 4
gpt4 key购买 nike

当发生错误时,我想抛出大约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继承的类

最佳答案

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

Exception||-MyGenericException|  |-MyFooException|  |-MyBarException||-OtherGenericException     |-OtherFooException   |-OtherBarException

See, that some exception classes do not directly inherit from the Exception, however they have a parent class which, in tern, is derived from the Exception.

A sample code is in C# written in notepad but hopefully you can get the idea.

2 more general exception classes inherit from Exception. They are MyIOException and MySecurityException. The other four less general classes derive from them.

//------------ 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;}
}

关于.net - 使用自定义异常类抛出多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11099631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com