w0051977
w0051977

Reputation: 15807

TRY CATCH THROWS exception without logging

I am looking through someone elses code and there is plenty of code like this:

try
   'Logic here
catch e as exception
throw
end try

I believe that the TRY and CATCH cause are pointless (they were probably used for debugging). Is there ever a scenario were coding like this is good practice?

There is a global even handler (global.asa).

Upvotes: 0

Views: 539

Answers (4)

Douglas Barbin
Douglas Barbin

Reputation: 3615

Generally, you don't want to do this (and you don't want to catch System.Exception either).

That being said, there might be some cases where you want to Throw the exception further up the call stack, and Catch it elsewhere. Here is a trivial example:

Try
   ' Do some stuff here.  For this example, let's assume 
   ' it cannot cause any exceptions       
   Try
       ' Do some other stuff here that CAN cause an exception
   Catch innerEx as Exception
       ' Rethrowing so that the outer block handles this
       Throw
   End Try
Catch ex as Exception
   MessageBox.Show("I just caught an exception.")
End Try

IF you do something like this, common sense dictates that you should place a comment that states WHY you are doing this.

As I said, that is an overly trivial example, but a more common usage might be that you have a method that calls another method, and you want the first method to handle any exceptions that the 2nd method might throw. The behavior will be the same if you leave the Try/Catch block out of the 2nd method instead of rethrowing, but the Try/Catch and the comment make your intent a little more obvious.

EDIT: If you know which line of code is likely to throw the exception, then putting a comment above that line is probably preferable to adding the Try/Catch blocks.

Upvotes: -1

Blindy
Blindy

Reputation: 67378

I have the exact same thing in one of the programs I inherited and it's actually worse because catching is expensive in C# (only trying is free). I made it a point to remove a dozen of these every day, I should be done in a few more weeks.

Upvotes: 1

JoelC
JoelC

Reputation: 3754

I agree that these clauses are pointless and worse, add clutter to your code that adds nothing other than confusion.

Worse still: if they ever do Throw e instead of just Throw the stack on the original exception is lost.

Upvotes: 3

UnhandledExcepSean
UnhandledExcepSean

Reputation: 12804

No. There is no reason to have a try..catch that only throws. If you want to debug and catch exceptions at the moment they occur, you should halt on framework exceptions within Visual Studio (Debug menu -> Exceptions...).

Upvotes: 2

Related Questions