首页 > 解决方案 > 未处理的异常,但是我有一个 Try catch

问题描述

我的应用程序通过一些类调用 web 服务。如果 web 服务返回 false,它将故意抛出 ApplicationException。

对 web 服务的调用是从按钮单击触发的,并调用一个方法来完成请求。此方法包括 Try/Catch 块,但是在 Visual Studio 2017 中调试时,ApplicationException 未处理。

对象图:

  • 点击事件调用 SendManifest()(在表单中)
  • SendManifest 创建一个对象并调用它的 sendManifest()
  • 此调用包含在 try catch
  • 另一个对象被实例化并调用 sendManifest()
  • 此函数接收来自 web 服务调用的结果。
  • 如果该结果为假,它会抛出带有结果消息的应用程序异常。

例子:

Private Sub SendManifest()
    Try
        Dim fi As New FreightInterface()
        fi.SendManifest(manifest)

    Catch ex As Exception
        Dim msg As String = "An exception occurred sending the manifest file: " & ex.Message
    End Try
End Sub
Public Class FreightInterface
    Public Function SendManifest(Byval manifest)
        Dim FreightIntegration
        FreightIntegration = New SubFreightIntegration()
        Return FreightIntegration.sendManifest(manifest)
    End Function
End Class
Public Class SubFreightIntegration
    Public Function sendManifest(ByVal manifest)
        Dim freight As Object = Nothing
        Select Case manifest.carrier
            Case "POST"
                freight = New PostFreight(manifest)
        End Select

        Dim r As Result = freight.sendManifest(manifest)
        If r.result Then 
           Return True
        Else
            Throw New ApplicationException(r.message)
        End If
End Class

我认为 PostFreight() 类中的 web 服务调用可能会导致问题,因为它是异步的并且需要等待。然而,异常消息是正确形成的,只是没有被捕获。

因此,我怀疑中间类 FreightInterface 无法正确传递异常。我的替代方法可能是简单地传递结果对象并在需要时抛出 FreightInterface。

标签: vb.net

解决方案


为了解决这个问题,我选择了两种方法:

如建议的那样,类现在指定返回类型,并且;我将 ApplicationException 推送到 FreightInterface 类中。能够处理该类的结果还有更多的实用性,所以我认为这是一个很好的解决方案。


推荐阅读