Exception catch clause skipped for an error? - c#

Something is fishy, and I know I must miss something.
I'm trying to connect to an Oracle instance, and due to firewalls, I cannot debug from my development machine. So, for now I'm writing to the event log.
My ASP.net page displays "Object reference not set to an instance of an object", and I'm trying to find the error.
The comments in the code points to my funny issue.
Here is a code sample:
try
{
OracleConnection oc = new OracleConnection(MyConnectionString);
//Event log successfully created
oc.Open();
//Event log NOT created, thus error occurred in previous statement (I would assume)
}
catch (Exception ex)
{
//Event log NOT created (?? - okay maybe there was no error)
}
finally
{
//Event log successfully created
}
So it seems like the catch clause are not called, therefor I would assume no error. But yet, I receive an error on the page.
The only other logical explanation is that the error occurs at the end of the finally clause or in the beginning of the catch clause, but the code to write the event log is the same as in the beginning.
So, what else can it be? Or perhaps, how else can I test it to find the error?

The problem statement turned out to be that the logging in the catch clause produced the error because ex.Message was null.

Related

Give user option to send error-report on uncaught exception

I've developed an application used by a third-party company.
Since I'm a horrible coder the application does still have some bugs which causes it to crash (unhandled nullpointerexception for example).
It's a Windows-forms application running on .NET 4.5 and now they are just getting the classic "An unhandled exception caused the app to terminate, press details for more info".
Trying to convince them that pressing "Details" and sending the stack-trace to me is really useful but they all seem reluctant.
Would it be possible to automate this behaviour, like show them a custom global "Exception catcher" where they can just press a button to send it to me by E-mail.
Inbefore "Global exception handling is bad" and "Why does your application throw nullpointerexceptions, you are a bad coder etc."
BR Tomas Anyuru
I guess the exceptions you get are unhandled.
Because of this, you will have to use the Application.ThreadException event to handle them. Because there is no .NET automatic mail sending and message display, you will have to implement your own inside this event.
Please have a look of an answer I wrote to have some examples of Exception catching strategies.
wrap your whole main() function in try-catch statement.
this way any un-handled exception will roll back and will be catched in your catch block:
static void main()
{
try
{
// the application code...
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show(
"Some error occured, please click ok to send it to the develpoer");
if (result = OK)
email(ex); // this is your function to send the email.
// useful information is also in ex.message
// here program will exit without error!
}
}
you can use log 4 net it is open source logging tools, use a lot by Java developer, and this version is specially for .Net http://logging.apache.org/log4net/
In addition to #Shamim code, you can wrap your main function in try, catch block, since the catch block here will track down the exception occurred inside any function called in the try block.
Shooting a mail inside catch block sometime throws and exception about Thread abort, so finally would be the right place to do so :
catch (Exception err)
{
mailBody = "Error: " + Convert.ToString(err.Message) + "<br /> Source: " + Convert.ToString(err.Source);
//Can display some message to user in an Literal Control from here.
}
finally
{
if (!string.IsNullOrEmpty(mailBody))
{
mailObject.To.Add(mailTo);
mailObject.CC.Add(mailCc);
mailObject.Body = mailBody;
MailService(mailObject);
}
}
MailService is a method to send mail which accept a MailObject as parameter.

How can I add a message to an exception without losing any information in C#?

I have the following code:
catch(Exception ex)
{
throw new FatalException("An error occurred while trying to load the XSLT file.", ex);
}
This unfortunately just swallows up the Exception. I can fix this by doing the following:
catch(Exception ex)
{
throw;
}
But I would still like to include the custom message for help with event logging.
How do I add this message to the exception without losing any information? (stack trace/debug symbols, etc.)
If you just need to add information to the original exception, such as a user-readable message or specific details that will be useful to you in tracking down the error but that won't be useful to the end user, you can make use of the Exception's Data property, which is a key/value pair dictionary.
We use this extensively in order to record information such as the report being executed or file that is being processed so that operations can determine what exactly was happening at the time of the error. The user doesn't need this detail since they are working directly with the cause of the failure.
You could also use this to pass a plain text message that makes sense to the user. The only issue is that you will have to perform some additional work in your logging framework or end-user interface in order to extract the data and make it useful to the consumer.
For example, you could do:
catch (Exception ex)
{
ex.Data.Add("UserMessage", "An error occurred while trying to load the XSLT file.");
throw;
}
Then in the client-side code, you could test to see if UserMessage exists and, if so, present it to the user instead of the Exception:
catch (Exception ex)
{
if (ex.Data.Contains("UserMessage"))
{
MessageBox.Show(ex.Data["UserMessage"].ToString());
}
else
{
MessageBox.Show(ex.Message);
}
}
That original Exception is still there.
When you do your Exception logging, the Exception that you receive will be the FatalException that you made with your message. The original Exception is in ex.InnerException. You can continue to cycle through InnerException until it's null to get all of the Stack Trace information, etc.
In short, don't.
I'm sure you could find some way of getting around this with some reflection, but I would strongly caution you against this. It goes against the original design of exceptions in .NET. Exceptions are not just there to help with logging, they provide information about the original cause of an application failure.
Using the first option is generally preferred as it maintains the stack trace of the original exception but allows you to provide additional information by wrapping it in a separate exception. In my own code, whenever I log exceptions, my logging function will recurse through the InnerException property to find every bit of useful information possible about the error.
Just in case someone needs a good answer. The key is to use AppDomain.CurrentDomain.FirstChanceException
The you can create a custom object with IDisposable to put all info in it. And if exception happens then FirstChanceException handler gets that info and populate Exception.Data.
Use Local Thread Storage to make it thread safe. Then down the line the code that catches it will get the data and log it.
Example:
using(MyCustomMessage.EnterToLocalStorage("Info for logging"") )
{
...code
...exception thrown
.... FirstChanceException examines local thread storage and get's "info for logging" and puts into Exception.Data.
}
//Dispose is called and all messages that were put into LocalStorage are removed.
//So if exception was not thrown before then it like nothing happened.
Google AsyncDiagnosticStack for a good example. https://github.com/StephenCleary/AsyncDiagnostics/blob/master/src/Nito.AsyncEx.AsyncDiagnostics/AsyncDiagnosticStack.cs

Proper way of using try catch() in C#

I am using ASP.NET/C#.
Here is an example where I am updating some information in database using lambda expression.
try
{
using (var db = new DataClasses1DataContext())
{
var logSubGroup = db.sys_Log_Account_SubGroups
.SingleOrDefault(subGroup => subGroup.cSubGroupName.Equals(subGroupName));
logSubGroup.cRejectedBy = rejectedBy;
logSubGroup.dRejectedOn = DateTime.Now;
logSubGroup.cAuthorizedStatus = "Rejected";
db.SubmitChanges();
}
}
catch (Exception ex)
{
}
As you can see I am not doing anything inside catch() block.
I know this is a terrible way of using try catch.
Can anyone just help me to use try catch block in a correct manner.
I am just clueless as to what must come inside the catch block.
Any suggestions are welcome.
Don't use a try-catch block at all, unless you have a specific reason to catch a specific exception.
Instead, use one of the global exception handling methods (Application_Error in ASP.NET) to globally catch unhandled exceptions, show an error message and log the error.
As a general rule, there is no need to catch an exception if the code catching the exception cannot do something about the problem, then continue running correctly. In code like what you've presented, can you identify some action you could take within the catch block to restore the program to a state where you trust it to continue running? If not, then just let the exception bubble up the stack.
You should ideally handle the error so that your application can recover from it, at the very least though, you should log it. You should never just swallow it. Also, you shouldn't handle an exception that you don't expect or can't handle. For example, when opening a file, a FileNotFoundException can be expected and handled, for example by displaying a warning and letting the user pick another file.
Theoretically it's up to you to decide what kind of exception may occur inside your catch statement it's not totally wrong doing it this way of course if you are in the development phase I would highly not recommend doing try catch since you can miss some of the important exception that may occur and you would want to fix also in general you should include a message or an action that should occur if the exception or error was caught a message to the user can be notified that action did not executed well but ideally you have to let user know what went wrong so in this case better error handling is a way to go

ExecutionEngineException not caught

I am curious why ExecutionEngineException is not caught when I am executing the code below.
try
{
((Window)window).Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
The WriteLine will never be reached. Any ideas how to catch this exception ?
Note: I know the exception is thrown by AvalonDock when one of DockablePanes is in AutoHide mode, is visible and user is trying to close wpf window.
Update:
I've read the remarks section on msdn regarding this exception:
The CLR never throws this exception in such a way that managed code can catch it.
So the question is how to close application nicely after something like that.
The ExecutionEngineException represents a fatal error from which you should not try to recover or handle. You need to tackle this at the source of the problem before it happens and not try to handle it gracefully.
Since you say you already know the source of the problem you should take actions to prevent the application to reach the state where its forced to throw the fatal exception.
Consider adding [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions()] attribute to the method that your code is executed.

Try/Catch block not catching Exception

I have a statement inside a try/catch block, but the exception is not getting caught. Can anyone explain?
Exception Details:
System.NullReferenceException: Object
reference not set to an instance of an
object.
Source Error:
Line 139: try
Line 140: {
Line 141: return (int)Session["SelectedLeadID"];
Line 142: }
Line 143: catch (Exception ex)
Update
This is an ASP.NET application. In the catch block, a new exception is thrown. The code you see is what is displayed on the ASP.NET error page.
That catch block should catch the exception, but make sure there's no re-throwing in there.
Another small comment: I've been tricked quite a few times by VS, cause it breaks on exceptions like that while running in debug-mode. Try to simply press 'continue' or 'F5' and see if your application doesn't work anyway :)
I suspect you're going to need to add more detail - that isn't reproducible just from your code. In particular (as already noted) we'd need to see inside the catch, and verify that the exception is actually being thrown from inside the try and not somewhere else.
Other possibilities:
you have dodgy code inside the exception handler that is itself throwing an exception
you have a dodgy Dispose() that is getting called (using etc)
you are in .NET 1.1 and the thing getting thrown (in code not shown) isn't an Exception, but some other object
If it is only the debugger breaking on the exception and you are using VS2005 or above, you might want to check under Debug->Exceptions... if any of the Common-Language-Runtime-Exceptions are activated. If so, the debugger will always catch the exceptions first, but you are allowed to continue.
To revert to normal execution, simply uncheck the apropriate exceptions from the list.
I also faced this problem
Image
which was solved by removing the tick of
"Break when this exception type is thrown."
Warning:
Of course, I am not aware of the consequences of this.
I've also had such an issue and it was driving me nuts for quite some time, but in the end I figured it out. It's quite stupid, but maybe it might help someone:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter"), "SecondParameter"); //comma placed in the wrong spot
}
catch (Exception ex)
{
//some code
}
}
It should have looked like:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter", "SecondParameter"));
}
catch (Exception ex)
{
//some code
}
}
Since I had many return statements in that function I didn't catch this right away.
Also, the error message I've been receiving wasn't quite what I have expected at first, but now it makes sense:
System.InvalidOperationException: Property
'JsonResult.SerializerSettings' must be an instance of type
'Newtonsoft.Json.JsonSerializerSettings'.
The code looks terribly ugly IMO. For there to be something in the catch() block means you are going to have another return ... statement which AFAIK you should always have a single return statement at the end of each function to make following code easier.
i.e. maybe your code should look like
public int Function()
{
int leadID = 0;
try
{
int leadID = (int)Session["SelectedLeadID"];
}
catch (Exception ex)
{
...
}
return leadID
}
Single exit points are supposed to make the code easier to follow, I guess? Anyway, to get any useful help you have to post more of the function.

Categories