【问题标题】:Handling custom exceptions in VB.net console applications在 VB.net 控制台应用程序中处理自定义异常
【发布时间】:2012-02-14 15:05:30
【问题描述】:

我正在开发一个我继承的应用程序,它内置了很多过于广泛的异常,它使用 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

结束模块

【问题讨论】:

  • "我没有进入 finally 块" --> finally 块总是运行,不管有没有异常。
  • 对不起,你就在那儿。它确实做到了最后 - 这是我试图弄清楚的未处理的异常触发。我将重新表述这个问题......但我真的很好奇为什么我会从我的自定义异常中生成一个未处理的异常。

标签: vb.net syntax exception-handling


【解决方案1】:

在 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 语句会使代码更难遵循。

【讨论】:

  • 哦,这很有道理。为什么这个简单的解释没有出现在 MSDN 中的任何结构化错误处理页面(我可以找到)上,我无法理解。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 2022-07-07
相关资源
最近更新 更多