Reputation: 14899
I would like to catch an exception an tell if it was me that deliberately threw the error or something else like a runtime error (object not instance of an object).
try
{
throw new Exception("throw this", "these can be many possible values");
}
catch (System.Exception ex)
{
if (IThrew) // <--- how can i tell if i threw or not?
{
exReport = "one thing"; // <--- Should go in here in this example.
}
else
{
exReport = "another thing";
}
throw new FaultException<ExceptionReport>(exReport, new FaultReason(ex.Message), new FaultCode("Receiver"));
}
Clarification:
I need keep record of all the exceptions then at the end display them in an exceptions report (array of exceptions). This is part of a schema I am REQUIRED to follow. (so please don't ask me to do it another way).
I have it all working great it outputs something like:
...
<soap:Detail>
<ows:ExceptionReport>
<Exception exceptionCode="…" locator="…">
<ExceptionText>…</ExceptionText>
</Exception>
<Exception exceptionCode="…" locator="…">
<ExceptionText>…</ExceptionText>
</Exception>
</ows:ExceptionReport>
</soap:Detail>
...
The problem is that when i'll have a few errors already in my ExceptionReport, then a runtime error will occur.
But i've realized i'm going the wrong way about this... as Gary mentioned... i shouldn't be using exceptions as flow control.
Upvotes: 1
Views: 181
Reputation: 6109
You could look at the call stack on the exception and see if the top of it is your code - if so you directly produced the exception but there is no way to tell if you used a throw
or, say, divided an int by zero
as the others have said the only sure fire way is to throw exceptions that could not be thrown by anyone else - ones that you control and have a common distinct base class
Upvotes: 0
Reputation: 498972
You can't tell why an exception was thrown.
What you can do is create your own exception classes so you can catch them - these will be the exceptions thrown on purpose. That is, since you created the exception class, the framework is not going to throw these.
try
{
// something
}
catch(MyCustomException ex)
{
// Thrown by Application logic
}
catch(System.Exception ex)
{
// Could by thrown by anything
}
Upvotes: 4
Reputation: 65126
Use a special type of exception for your own exceptions and check for that.
Otherwise you'd have to resort to inspecting stack traces to see if the origin is one of your assemblies, which is both ugly and unreliable.
Upvotes: 5