Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# throw statement redundant?

Tags:

java

c#

exception

I have a code that looks like this (sorry for the Java bracket style):

class SomeClass {
   public static void doSomethingRisky() {
        try {
          SomeRiskyFunction();
        } catch (Exception e) {
          throw e;
        }
   }
}

class MainClass {
   public void callSomethingRisky() {
        try {
          SomeClass.doSomethingRisky();
        } catch (Exception e) {
          FinallyHandleTheException(e);
        }
   }
}

Basically, SomeClass will be a library and I want to design it so that all exceptions will be handled by the calling program (who may or may not choose to display a message about the exception).

My question is about the use of try/catch&throw in the doSomethingRisky() from SomeClass. Is it redundant or is it necessary? I mean, if I leave it off and the function does encounter an Exception during runtime, will it crash the program because nothing catches the Exception inside THAT function, or does it still pass it to the caller (callSomethingRisky()) where it is gracefully handled?

Same question for Java. Thanks!

like image 526
Bogdan Alexandru Avatar asked Jul 23 '26 06:07

Bogdan Alexandru


2 Answers

The try/catch with throw e; in doSomethingRisky does exactly one thing: it destroys the stack-trace information. That probably isn't what you wanted, so the try/catch should be removed - it will already bubble-up as expected.

For info, if it was just throw; (rather than throw e;) then it would merely be redundant, rather than destructive.

like image 88
Marc Gravell Avatar answered Jul 25 '26 18:07

Marc Gravell


It will pass to the caller in both ways.
One of the uses of the construct you show above is to log the exception in the procedure, but still throw it so somewhere up the call stack a catch can handle the exception.

One thing to keep in mind, use throw in this situation instead of throw e to avoid loosing stack trace information.

like image 33
Mr47 Avatar answered Jul 25 '26 18:07

Mr47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!