0

I am forever finding try-catch blocks like the following in our code:

public void method()
{
   try {
      //some code
   } catch(Exception ex) {
     throw ex;
   }
 }

What is the need for the try-catch and can someone tell me why we shouldn't do this?

Daniel Loudon
  • 799
  • 3
  • 18
  • 1
    This is the worst try catch pattern you can write. It does nothing except lose the stack trace when the exception bubbles up. While I can't think of any reason to do this, I suppose if you **want** to lose the stack trace this is what you would do. – Crowcoder Oct 06 '18 at 12:26
  • See answer to question https://stackoverflow.com/questions/881473/why-catch-and-rethrow-an-exception-in-c – unlut Oct 06 '18 at 12:27
  • I already thought this, just wanted it confirmed that they were indeed useless – Daniel Loudon Oct 06 '18 at 12:27
  • It's not useless. There are actual reasons for wanting to reset the stack trace – Camilo Terevinto Oct 06 '18 at 12:35
  • This code will not show you any special result. In a Multi-Layered application I doing this to pass a custom message for each type of exceptions to upper layer. in this way i can do multi-language error support and more user-friendly messages. so it's useful to formatting error messages for the end user, or Support team I think. – RezaNoei Oct 06 '18 at 12:43
  • I assume you are throwing a custom exception within your `try` block though. – Daniel Loudon Oct 06 '18 at 12:46

0 Answers0