Why catch an exception just to throw it again?

In a webservice I see this code:

<WebMethod()> _
Public Function dosomething() As Boolean
    Try
        If successful Then
            Return True
        Else
            Return False
        End If
    Catch ex As Exception
        Throw ex
    End Try
End Function

What's the point of catching the exception and just throwing it again? Do I miss something?

Edit: Thanks for the answers! I thought it was something like that, but wasn't sure if I could/would refactor those away without any implications.

Answers


I can think of no reason to do this for functionality. However, it can arise when previously there was some error handling (logging usually) that has been removed, and the developer removed the log handling but did not restructure the code to remove the redundant try/catch.


Don't do this.

If you absolutely need to rethrow the exception, just use throw; using throw ex; erases the stack trace and is absolutely wrong.


Probably a bit of code left over from debugging (you'd set a breakpoint on the throw so you could examine the exception in the debugger). I might do something like this if I wanted to log the exception and then pass it up the chain, although I'd probably wrap the exception in another one with a more meaningful (to my application) error message.


One of the architectures (design patterns) I could see this being used in is where a transaction is being handled. The function does its work, fails, and the catch block completes the transaction to a known state (usually a roll back) and then throws a user-defined exception.

As it stands now, refactor that code to a more sane state.


Not only is the try/catch pointless, but so is the IF. The whole function could be reduced to one line:

return successful

At which point, why bother? Why not just test "successful" instead of calling the function?

Well, okay, it's a Web Method, I guess you need the function just to give Ajax or whomever a handle.

(Yes, I'm aware my answer is 7 years late. I just stumbled across this when searching for something entirely unrelated.)


The pattern for Monitor makes this very likely to rethrow an error as you need a finally to ensure Monitor.Exit is called

https://msdn.microsoft.com/en-us/library/4tssbxcw(v=vs.110).aspx

Dim lockObj As New Object()

If Monitor.TryEnter(lockObj) Then
    Try
        ' The critical section.
    Catch
       throw
    Finally
       ' Ensure that the lock is released.
       Monitor.Exit(lockObj)
    End Try
End If

You may want to do it if you want to catch an exception except a sub-class of it.

For example,

try {
    // Something stupid
}
catch(RuntimeException e) {
    throw e; //Handle it outside
}
catch (Exception e) {
    // I'm dead
}

Need Your Help

PNRP Global_ stuck on Alone

.net cmd p2p pnrp

I have two installations of Windows 7. a 64bit version on my hard disk, and a 32bit version installed as a bootable VHD.