throw new Exception while keeping stack trace and inner exception information - c#

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.

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;
}

Related

elmah.axd custom exception message with stacktrace of child throwed exception in C#

What I want to achieve is to show a custom exception Type and Error message in elmah.axd table but with the original stacktrace of a child throwed exception.
This is just an example of a nested try catch that match my needs:
// custom exception constructor
public MyCustomException(string customMsg, Exception expt):base(customMsg,expt)
// my test case
try{
try{
//_context.saveChanges(); --> this will generate an exception
// but for this example we'll throw the following
throw new IndexOutOfRangeException();
}
catch (Exception e){
// here elmah will print in the Type column "IndexOutOfrange" and in the Error column the message: "Index was outside the bounds of the array. Details..."
ErrorSignal.FromCurrentContext().Raise(e);
// now I throw a custom exception with the original stacktrace of "IndexOutOfrangeException"
throw new MyCustomException("Message to see in elmah 'Error' column", e)
}
}
catch(MyCustomException cex){
// here elmah will also print in the Type column "IndexOutOfrange" and in the Error column the message: "Index was outside the bounds of the array. Details..." with the original stacktrace
ErrorSignal.FromCurrentContext().Raise(cex)
// my expectation would be to print in the Type column "MyCustomException" and in the Error column the message: "Message to see in elmah 'Error' column Details..." with the original stacktrace
}
catch(Exception ex){
// some code here
}
Am I doing something wrong or it's just not possible what I want?
ELMAH always uses the base exception to generate the Type and Error fields. This is the best (IMO) way of doing it since the base exception will always be the original cause of the error. This explains why you get the type and message of the IndexOutOfRangeException logged in ELMAH.
There's a small "hack" to resolve this if you switch to using the Log method:
try{
try{
throw new IndexOutOfRangeException();
}
catch (Exception e){
throw new MyCustomException("Message to see in elmah 'Error' column", e)
}
}
catch(MyCustomException cex){
var error = new Elmah.Error(cex);
// Type and Error will now have the values of `IndexOutOfRangeException`
error.Type = cex.GetType().FullName;
error.Message = cex.Message;
// I manually updated the values from `MyCustomException`
ErrorLog.GetDefault(HttpContext.Current).Log(error);
}
catch(Exception ex){
// some code here
}
I tested this locally and both Type and Error get the value from the outer exception.

Get the actual StackTrace object from an Exception

An Exception object has a StackTrace property on it. But it is just a string.
Is there a way to get an actual System.Diagnostics.StackTrace object from an Exception?
I ask because I am getting the Exception object from an UnhandledExceptionEventHandler and I don't have access to the frame that generated the exception to get an actual Stack Trace.
try{
//some code
}
catch (Exception ex){
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ex);
}

Exception not catching when using Custom Exception classes in ASP.NET MVC and C#

I have created few custom exception class
public class CreateNewUserWebException : Exception
{
public CreateNewUserWebException(string email): base(
string.Format("[{0}] - User could not be added.", email))
{
}
}
public class CreateNewUserEntityFrameworkException : System.Data.DataException
{
public CreateNewUserEntityFrameworkException(string email)
: base(
string.Format("[{0}] - User could not be added.", email))
{
}
}
and here is my controller code
try
{
var user = _createUserModule.CreateUser(model);
CookieManager.SetAuthenticationCookie(user, model.Email, rememberMe: false);
return RedirectToAction("Index", "Bugs");
}
catch (CreateNewUserEntityFrameworkException exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
catch (CreateNewUserWebException exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
catch(Exception exception)
{
this.ModelState.AddModelError("", "Some error occured while registering you on our sytem. Please try again later.");
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
I have purposely fully induced an primary key violation exception which is
but exception is not catched by my custom exception class. It is not caught by the last exception catch block.
I cannot understand why so. Can some one help me out on this please.
The part you've highlighted in the debugger is the inner exception. That isn't used by the CLR to determine which catch block to enter. The outer exception is just a DbUpdateException - which you haven't specified a particular catch block for.
Even the inner exception is just a DataException - it's not an instance of your custom exception.
You haven't shown any code which actually throws your exception - are you sure it's being used at all? What code have you written to tell EF to throw your exception rather than the exception it would otherwise throw?
(Given your comments, I'm not sure you quite understand exception handling. Creating a custom exception doesn't somehow let you catch an instance of that without it being thrown - something still has to throw an instance of that exception before it's any use.)

OutOfMemory exception on Exception.ToString()

Below is some logging output from a .NET application.
Error in MainFunction.
Message: Exception of type 'System.OutOfMemoryException' was thrown.
InnerException:
StackTrace: at System.Text.StringBuilder.ToString()
at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Exception.GetStackTrace(Boolean needFileInfo)
at System.Exception.ToString(Boolean needFileLineInfo)
at System.Exception.ToString()
[the rest of the trace is removed]
Which corresponds to the following line of application code. The following is in a catch block, and returns the string to the method that actually throws:
private void MainFunction()
{
...
try
{
string doc = CreateXMLDocument(); // <- Out of Memory throws here
}
catch (Exception ex)
{
CoreLogging("Error in MainFunction.", ex);
}
}
private string CreateXMLDocument()
{
try
{
//Some basic and well constrained XML document creation:
...
}
catch (Exception ex)
{
return "Exception message: " + ex.ToString(); // <- This is the last line of the trace
}
}
What should I make of this? Clearly Exception.Message should be used instead of Exception.ToString(), but I'd still like to understand this. Does
at System.Text.StringBuilder.ToString()
at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
mean that the stack trace of the exception in CreateXMLDocument was so mammoth caused OutOfMemory? I'm curious to see how that would occur as there's definitely no circular calls in CreateXMLDocument, which is the only thing I can think of that could cause an enormous stack trace.
Has anyone else encountered a similar situation?
I little bit of guessing:
1) CLR rises a OutOfMemoryException. 2) You catch this exception and call .ToString on it
3) ToString() tries to allocate memory to the stack trace but... there is no memory and another OutOfMemoryException is rised.
In the comments you said that the XML documents have a few hundreds of kbytes, this could be a/the problem if your server run on 32bits, because of the fragmentation of the LOH.

Difference between 'throw' and 'throw new Exception()'

What is the difference between
try { ... }
catch{ throw }
and
try{ ... }
catch(Exception e) {throw new Exception(e.message) }
regardless that the second shows a message.
throw; rethrows the original exception and preserves its original stack trace.
throw ex; throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.
NEVER write throw ex;
throw new Exception(ex.Message); is even worse. It creates a brand new Exception instance, losing the original stack trace of the exception, as well as its type. (eg, IOException).
In addition, some exceptions hold additional information (eg, ArgumentException.ParamName).
throw new Exception(ex.Message); will destroy this information too.
In certain cases, you may want to wrap all exceptions in a custom exception object, so that you can provide additional information about what the code was doing when the exception was thrown.
To do this, define a new class that inherits Exception, add all four exception constructors, and optionally an additional constructor that takes an InnerException as well as additional information, and throw your new exception class, passing ex as the InnerException parameter. By passing the original InnerException, you preserve all of the original exception's properties, including the stack trace.
The first preserves the original stacktrace:
try { ... }
catch
{
// Do something.
throw;
}
The second allows you to change the type of the exception and/or the message and other data:
try { ... } catch (Exception e)
{
throw new BarException("Something broke!");
}
There's also a third way where you pass an inner exception:
try { ... }
catch (FooException e) {
throw new BarException("foo", e);
}
I'd recommend using:
the first if you want to do some cleanup in error situation without destroying information or adding information about the error.
the third if you want to add more information about the error.
the second if you want to hide information (from untrusted users).
One other point that I didn't see anyone make:
If you don't do anything in your catch {} block, having a try...catch is pointless. I see this all the time:
try
{
//Code here
}
catch
{
throw;
}
Or worse:
try
{
//Code here
}
catch(Exception ex)
{
throw ex;
}
Worst yet:
try
{
//Code here
}
catch(Exception ex)
{
throw new System.Exception(ex.Message);
}
Throwing a new Exception blows away the current stack trace.
throw; will retain the original stack trace and is almost always more useful. The exception to that rule is when you want to wrap the Exception in a custom Exception of your own. You should then do:
catch(Exception e)
{
throw new CustomException(customMessage, e);
}
None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:
using System;
using System.Collections.Generic;
namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
void fail()
{
(null as string).Trim();
}
void bareThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw;
}
}
void rethrow()
{
try
{
fail();
}
catch (Exception e)
{
throw e;
}
}
void innerThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw new Exception("outer", e);
}
}
var cases = new Dictionary<string, Action>()
{
{ "Bare Throw:", bareThrow },
{ "Rethrow", rethrow },
{ "Inner Throw", innerThrow }
};
foreach (var c in cases)
{
Console.WriteLine(c.Key);
Console.WriteLine(new string('-', 40));
try
{
c.Value();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
Which generates the following output:
Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
--- End of inner exception stack trace ---
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).
The output of the rethrow case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e (line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.
The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).
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.
BlackWasp has a good article sufficiently titled Throwing Exceptions in C#.
throw is for rethrowing a caught exception. This can be useful if you want to do something with the exception before passing it up the call chain.
Using throw without any arguments preserves the call stack for debugging purposes.
Your second example will reset the exception's stack trace. The first most accurately preserves the origins of the exception.
Also you've unwrapped the original type which is key in knowing what actually went wrong... If the second is required for functionality - e.g., to add extended information or rewrap with a special type such as a custom 'HandleableException' then just be sure that the InnerException property is set too!
Throw;: Rethrow the original exception and keep the exception type.
Throw new exception();: Rethrow the original exception type and reset the exception stack trace
Throw ex;: Reset the exception stack trace and reset the exception type
If you want you can throw a new Exception, with the original one set as an inner exception.
Most important difference is that the second expression erases the type of the exception. And the exception type plays a vital role in catching exceptions:
public void MyMethod ()
{
// both can throw IOException
try { foo(); } catch { throw; }
try { bar(); } catch(E) {throw new Exception(E.message); }
}
(...)
try {
MyMethod ();
} catch (IOException ex) {
Console.WriteLine ("Error with I/O"); // [1]
} catch (Exception ex) {
Console.WriteLine ("Other error"); // [2]
}
If foo() throws an IOException, the [1] catch block will catch the exception. But when bar() throws IOException, it will be converted to plain Exception and won't be caught by the [1] catch block.
throw or throw ex, both are used to throw or rethrow the exception, when you just simply log the error information and don't want to send any information back to the caller you simply log the error in catch and leave.
But in case you want to send some meaningful information about the exception to the caller you use throw or throw ex. Now the difference between throw and throw ex is that throw preserves the stack trace and other information, but throw ex creates a new exception object and hence the original stack trace is lost.
So when should we use throw and throw e? There are still a few situations in which you might want to rethrow an exception like to reset the call stack information.
For example, if the method is in a library and you want to hide the details of the library from the calling code, you don’t necessarily want the call stack to include information about private methods within the library. In that case, you could catch exceptions in the library’s public methods and then rethrow them so that the call stack begins at those public methods.

Categories

Resources