What is the point of this Catch statement?

I seen this in legacy code. What, if any, is the purpose of a single Throw within a Catch?

       Try
           'Some Oracle access statement
       Catch err As OracleClient.OracleException
            Throw
       Finally
          'Do something
       End Try

Is the outcome the same as if the original error was not caught? Would you use a Throw statement w/o parameters to re-throw the original error, typically after performing some action first?


It looks like it is being used to bubble the error up. While one would normally put more in the catch statement than just throw (ie logging, alerts, etc.) in this case it is allowing a finally statement to be used to do some cleanup then bubbling the error up to the next level. Without the try/catch how would this cleanup code be written at this scope? As someone mentioned already the throw syntax (without ex) is preserving the stack trace.


I've often used that pattern when debugging; I'll set a breakpoint on the throw statement so I can inspect err . Not sure if there's another good reason to do this though.


Many people think it's a no-op, but it's not. If you have this program:

Module Module1
    Function Filter() As Boolean
        Console.WriteLine("1")
        Return True
    End Function

    Sub Thrower()
        Try
            Throw New Exception("x")
        Finally
            Console.WriteLine("3")
        End Try
    End Sub

    Sub NoCatch()
        Try
            Thrower()
        Finally
            Console.WriteLine("2")
        End Try
    End Sub

    Sub WithCatch()
        Try
            Thrower()
        Catch ex As Exception
            Throw
        Finally
            Console.WriteLine("2")
        End Try
    End Sub

    Sub Caller(ByVal method As Action)
        Try
            method()
        Catch ex As Exception When Filter()
        End Try
    End Sub

    Sub Main()
        Console.WriteLine("No Catch")
        Caller(AddressOf NoCatch)
        Console.WriteLine("With Catch")
        Caller(AddressOf WithCatch)
    End Sub
End Module

The output is

No Catch
1
3
2
With Catch
3
1
2

Edit: One scenario when this actually matters this: The Thrower and NoCatch functions are in the same assembly, which is thrusted. The Caller method is not trusted and malicious. Now imagine that the Thrower method uses WindowsIdentity to impersonate another user, which the untrusted assembly is not allowed to do. It then relies on a using block (= try/finally) to unimpersonate the user, but it throws an exception. This would mean that the malicious assembly runs as the impersonated user during the execution of the Filter method. Perhaps this will also work if asserting permissions, but I'm not sure.

链接地址: http://www.djcxy.com/p/79852.html

上一篇: vshost.exe文件的用途是什么?

下一篇: 这个Catch声明有什么意义?