Yes, the two are different. The throw
will modify the stack trace information in the Exception
object - so your second example will still produce an exception, but without the stack trace information.
Exception
-derived classes are classes as any other - all the "magic" happens with the throw
keyword.
This is also the reason why it's a bad idea to rethrow the exception by doing throw ex;
- you either want to use throw;
(although careful about the issue of rethrowing in the same method that Xanatos pointed out), or you want to wrap the inner exception (ie. throw new MyException(ex)
). In both cases, there's still some minor changes that can complicate debugging, but if you're well prepared, it helps a lot.
This behaviour is actually quite useful. For one, it means that you can have helper methods that construct exceptions for you to throw (this is used all over the place in .NET code itself). Two, it allows the runtime to actually throw exceptions like StackOverflowException
and OutOfMemoryException
- both have their instances created when the application starts, and when the issue occurs, they only throw - a new
would fail, of course.