Exceptions for re-throwing C #

If throwing exceptions between several methods, should all methods throw an exception again? eg

Method1() { Method2(); } Method2() { try { // Do something } catch { throw; } } 

 try { Method1(); } catch { // Do something about exception that was thrown from Method2() } 

Note that in Method1() I didn't need to wrap Method2() in a try block, should I be?

+6
source share
2 answers

You do not need to check, catch, and discard exceptions if you have any particular reason for catching them in the first place. Otherwise, they will automatically receive bubbles from the lower level functions, which pass them to the highest level in your code. Essentially, you can think of them as “instilling,” even though this is not technically what is happening.

In fact, most of the time when you see a try / catch , it is incorrect. You should not catch exceptions if you cannot handle them. It is completely pointless (and actually considered bad practice) to catch exceptions, just to repair them. Do not complete all your code in try blocks.

Please note that by “processing them” I mean that your code in the catch will take some specific action based on the specific exception that was thrown, which tries to fix the exceptional condition.
For example, for FileNotFoundException you can tell the user that the file cannot be found, and ask them to select another.

See my answer here for more details and a detailed discussion of "best practices for handling exceptions."

+8
source

You do not need to wrap everything in try .

You should only try if you want to catch something, and you should catch something in the following cases:

  • Are you ready to handle the exception (do everything you need to do, and don't let it spread the stack),
  • You want to do something with an exception (e.g. log it) before restoring it (using a form with no throw parameters),
  • You want to add information about the exception by wrapping it in another exception from your own (see the comment by Allon Guralnek below).
+9
source

Source: https://habr.com/ru/post/892384/


All Articles