1

I got here that the next code is anti-pattern. Is it right?

try
{
//something
} 
catch(Exception e)
{
//something
}

And why better to use

try
{
//something
} 
catch(Exception e)
{
 //something
 throw;
}

?

I got that second variant is using for re-throwing exception (logging for example), but if I need re-throw the same exception why not use the next code?

try
{
//something
} 
catch(Exception e)
{
 //something
 throw e;
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
  • http://stackoverflow.com/questions/1697216/the-difference-between-try-catch-throw-and-try-catche-throw-e?rq=1 – Habib Jun 26 '14 at 13:10
  • You don't keep the stacktrace (f.e. the original line number) if you `throw e;` instead of `throw;`. The new stacktrace shows your empty `catch` block which is undesirable. An empty catch is bad practise anyway. – Tim Schmelter Jun 26 '14 at 13:11

1 Answers1

1

This will re-throw the same exception and keep the stack trace. This will make debugging easier.

catch(Exception e)
{
 //something
 throw;
}

This will rethrow the exception, but you'll lose the stack trace.

catch(Exception e)
{
 //something
 throw e;
}

This will silently swallow the exception. You only want to do this when you're catching a specific exception rather than Exception. You should generally have a good reason for doing so.

try
{
//something
} 
catch(Exception e)
{
//something
}
David Crowell
  • 3,711
  • 21
  • 28
  • Essentially, you should never throw an exception that you have caught, by name. You should either throw a new exception (optionally including the caught exception as an inner exception) or _rethrow_ using `throw` without an operand. – Xharlie Jun 26 '14 at 13:12
  • 1
    You've pointed out the difference between examples 2 and 3, which is already addressed in the other question linked in the comments. Asker is asking the difference between 1 and 2 first, and only asking about 2 and 3 in the context of trying to understand why 2 is better than 1. – starsplusplus Jun 26 '14 at 13:14