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.
"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" .
To keep the original stack trace information with the exception, use the throw statement without specifying the exception.
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.
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;
}
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