处理 VB.net 控制台应用程序中的自定义异常

发布于 2025-01-05 09:32:29 字数 1323 浏览 1 评论 0原文

我正在开发一个我继承的应用程序,它内置了很多过于广泛的异常,它使用 try/catch 块,但完全忽略异常(在大多数情况下)并跳过。我想封装一个更好的自定义异常模型,但我的自定义异常本身一直未得到处理。我将如何抛出一个可以记录的异常,并将异常标记为已处理以继续执行?

在示例中,我进入了finally 块,并且进入了ExpectedExeptionType。然而,它仍然抛出一个未处理的异常,该异常会通过弹出框停止线程执行。有没有办法让我抛出异常,用它来记录消息,然后继续处理(将我的异常算作处理它)?

示例:

Module Module1

Sub Main()

    Dim a As Integer
    Console.WriteLine("Please enter an integer and then press enter.")
    Try
        a = Console.ReadLine()
        Console.WriteLine("You entered the value " & a.ToString)
        Console.WriteLine("Press enter to continue")
        Console.ReadLine()
    Catch ex As Exception            
        Throw New ExpectedExceptionType("Bad")            
    Finally
        'Clean up objects/whatever and continue
        Console.WriteLine("TEST")
        Console.ReadLine()
    End Try

    Console.WriteLine("Hi there, press enter to exit!")
    Console.ReadLine()
End Sub

Public Class ExpectedExceptionType
    Inherits Exception

    Public Sub New()            
    End Sub

    Public Sub New(ByVal Message As String)
        MyBase.New(Message)
        Console.WriteLine("I know I'm getting into the exception.")
    End Sub

    Public Sub New(ByVal Message As String, ByVal Inner As Exception)
        MyBase.New(Message)
    End Sub

End Class

最终模块

I'm working on an application I inherited which has a lot of overly broad exceptions built in, it uses try/catch blocks but completely ignores the exception (in most cases) and steps over. I'd like to wrap in a better custom exception model, but my custom exception itself keeps coming back unhandled. How would I go about throwing an exception that I can log, and marking the exception as handled to continue execution?

In the example, I am getting into the finally block, and am getting into ExpectedExeptionType. It's still, however, throwing an unhandled exception which stops the thread execution with the pop-up box. Is there a way for me to throw the exception, use it to log the message, and continue processing (count my exception as handling it)?

Example:

Module Module1

Sub Main()

    Dim a As Integer
    Console.WriteLine("Please enter an integer and then press enter.")
    Try
        a = Console.ReadLine()
        Console.WriteLine("You entered the value " & a.ToString)
        Console.WriteLine("Press enter to continue")
        Console.ReadLine()
    Catch ex As Exception            
        Throw New ExpectedExceptionType("Bad")            
    Finally
        'Clean up objects/whatever and continue
        Console.WriteLine("TEST")
        Console.ReadLine()
    End Try

    Console.WriteLine("Hi there, press enter to exit!")
    Console.ReadLine()
End Sub

Public Class ExpectedExceptionType
    Inherits Exception

    Public Sub New()            
    End Sub

    Public Sub New(ByVal Message As String)
        MyBase.New(Message)
        Console.WriteLine("I know I'm getting into the exception.")
    End Sub

    Public Sub New(ByVal Message As String, ByVal Inner As Exception)
        MyBase.New(Message)
    End Sub

End Class

End Module

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月依秋水 2025-01-12 09:32:29

在 Catch 中,您抛出 ExpectedExceptionType 但从未处理它。假设您有这样的代码:

Sub Main()
    Try
        MethodWhichCanThrow()
    Catch ex as ExpectedExceptionType
        'Log exception here, but don't stop execution
        Console.WriteLine("Expected exception: " & ex.ToString())
    End Try
    'Some more code here
End Sub

Sub MethodWhichCanThrow()
    If someCondition Then
        Throw New ExpectedExceptionType("This error is expected")
    End If
    'Do something if there's no error here
End Sub

您可以看到我们有一个 Catch 语句,它仅捕获预期的异常类型。因此,在这种情况下,如果出现其他意外异常,它将崩溃,但如果出现预期错误,它将绕过 MethodWhichCanThrow 中的代码,但继续执行其余代码。

我还要补充一点,如果预期会出现某种错误情况,并且可以使用某种不会抛出异常的方法来验证此错误,那么最好使用此方法。例如,这样:

Dim number As Integer
If Integer.TryParse(value, number) Then
    Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
    Console.WriteLine("Conversion failed")
End If 

...比这样更好:

Dim number As Integer
Try
    number = Int32.Parse(value)
    Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
    Console.WriteLine("Conversion failed")
End Try

在这种情况下,try-catch 版本还不错,但您仍然必须知道抛出哪种类型的异常以及在哪种情况下抛出。此外,在现实世界的代码中,有大量的 try-catch 语句会使代码更难以理解。

In the Catch, you're throwing an ExpectedExceptionType but never handling it. Let's say you had such code:

Sub Main()
    Try
        MethodWhichCanThrow()
    Catch ex as ExpectedExceptionType
        'Log exception here, but don't stop execution
        Console.WriteLine("Expected exception: " & ex.ToString())
    End Try
    'Some more code here
End Sub

Sub MethodWhichCanThrow()
    If someCondition Then
        Throw New ExpectedExceptionType("This error is expected")
    End If
    'Do something if there's no error here
End Sub

You can see that we have a Catch statement which catches only the expected exception type. So in this case, if you have some other unexpected exception, it will crash, but if you have the expected error, it will bypass code from MethodWhichCanThrow but continue executing the rest of the code.

I will also add that if some error condition is expected, and if it's possible to validate this error with some method which doesn't throw, it's preferable to use this method. For example, this:

Dim number As Integer
If Integer.TryParse(value, number) Then
    Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
    Console.WriteLine("Conversion failed")
End If 

...is preferable to this:

Dim number As Integer
Try
    number = Int32.Parse(value)
    Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
    Console.WriteLine("Conversion failed")
End Try

In this case, the try-catch version is not too bad, but you still have to know which type of exception is thrown, and in which case. Also, in real-world code having a lot of try-catch statements makes code harder to follow.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文