Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw new Exception while keeping stack trace and inner exception information

I have a FileSystemWatch program that I'm working on and if there's an error copying a file, I want to be able to know which file it failed on. At the same time, I'd like to be able to retain the stack trace, as well as the inner exception information.

                if (!found)
            {
                try
                {
                    File.Copy(file, Path.Combine(watchDirectory, filename));
                }
                catch (Exception ex)
                {
                    WriteToLog(new Exception(
                        String.Format("An error occurred syncing the Vault location with the watch location. Error copying the file {0}. Error = {1}", file, ex.Message), ex.InnerException));
                }
            }

So, the exception that gets passed, I still want to have the stacktrace info that, the inner exception info, but I want the "message" to be my custom message that contains which file it failed on, while also displaying the "real" message that was thrown by the original exception.

like image 876
ganders Avatar asked Jan 13 '12 19:01

ganders


People also ask

What does throw new exception do?

"throw "and "throw new" Exception() In the above case, throws the original exception but resets the stack trace , destroying all stack trace information until your catch block. This means that, it excludes stack information from the point where you called "Throw ex" .

What statement should you use to Rethrow a caught exception named ex without losing the stack trace?

To keep the original stack trace information with the exception, use the throw statement without specifying the exception.

What is the difference between throw and throw ex?

The differences between throw and throws in Java are:The throw keyword is used inside a function. It is used when it is required to throw an Exception logically.


1 Answers

I changed the new exception to accept ex as the inner exception instead of ex.InnerException. If you call ToString() on your new exception instance, it will include the full stack trace and all inner exceptions.

try
{
    // ...
}
catch (Exception ex)
{
    string message = String.Format("An error occurred syncing the Vault location with the watch location. Error copying the file {0}.", file);
    Exception myException = new Exception(message, ex);
    string exceptionString = myException.ToString(); // full stack trace
    //TODO: write exceptionString to log.
    throw myException;
}
like image 193
jrummell Avatar answered Nov 13 '22 16:11

jrummell