Possible Duplicate:
difference between throw and throw new Exception()
I'm a programmer working on adding new functionality to legacy code. While debugging, I parsed over this Catch block, which got an angry "object not set to reference of object" notice from Visual Studio:
catch(Exception ex)
{
SporeLog.Log("Failed to create new SavedDocumentList with Name: " + name, ex);
throw;
}
What does it mean to "throw". I'm familiar with throw new [exceptiontype]...
but what does it mean to just... throw
?
Is this good practice, or should I alter this code to ease the trials of the developers after me?
And why does Visual Studio yell at me for doing this?
throw rethrows the caught exception, retaining the stack trace, while throw new Exception loses some of the details of the caught exception. You would normally use throw by itself to log an exception without fully handling it at that point.
A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement. The following example extracts source information from an IOException exception, and then throws the exception to the parent method. C# Copy.
Use try/catch/finally blocks to recover from errors or release resources. Use try / catch blocks around code that can potentially generate an exception, and your code can recover from that exception. In catch blocks, always order exceptions from the most derived to the least derived.
You can also omit the arguments on the catch block entirely. In this case, the catch block will catch all exceptions, regardless of their type. Because you don't declare an exception variable, however, you won't have access to information about the exception.
Yes it is a good practice.... what it does is, it re-throws the same exception that it catched, keeping the stacktrace intact.
It means "re-throw this same exception". In other words, continue bubbling up the exception to the next try/catch block.
It's useful if you can't actually deal with an exception at this level, but want to log that the exception happened.
Unfortunately, many people think "log & rethrow" should be done at every level, leading to applications which run slowly, have log files with every exception logged multiple times, and often never actual handle the exception.
This is a good practice (sometimes). It allows you to catch an exception, log it or determine if it can be handled, then rethrow it without losing the StackTrace.
Your NullReferenceException came from SporeLog
being null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With