Exception Handling error when saving to database - c#

Iam a newbie who needs help. When saving to a database, i get the following error:
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in (name of my application)
Please help me with steps to solve this one. Thank you in advance.

First chances exceptions will be shown if you have your Visual Studio settings set so that every CLR exceptions gets reported. This will include exceptions you actually handle.
In Visual Studio's menu, go to Debug > Exceptions and uncheck the Thrown option for Common Language Runtime Exceptions.
Of course that won't make the actual exception go away but you'll be allowed to handle it as you want:
try
{
// do your query
// commit current transaction if possible/necessary
}
catch (SqlCeException ex)
{
// handle exception here and rollback current transaction if possible/necessary
}
finally
{
// ensure proper disposal of any commands and connections you have
}
It goes without saying that you must ensure your query is properly written and that the server objects it tries to work with exists. You generally won't want to handle cases where a comma is missing or a field is not found, for instance. Exception handling must be for exceptional situations your code cannot control, like a faulted connection, a server malfunction, etc.

First of all you might want to check whehter your SQL query is syntactically correct.
Secondly you might want to read about how to handle exceptions in MSDN http://msdn.microsoft.com/en-us/library/0yd65esw.aspx with try-catch statement.
A small example looks like this.
try
{
// ... code which throws exception
}
catch (SqlCeException e)
{
// ... exception handling, e.g. logging, rolling back data,
// telling the user something went wrong, you name it
}
Last but not least you might want to debug your application step by step to see what is causing the error and what the actual SQL Query is throwing the exception.

Related

Should we put try catch with function if we just want to log the exception?

In asp.net application, all the exception that occurs and are not inside try catch can be handled by application_error.
If we just need to log the exception along with its stack trace, and we need not make any other decision/logic inside catch, why should we put try catch at application/bl or dal layer functions? Is there any reason to put try/catch with every database call function?
For example we have hundreds of function in DAL layer that executes following code:
try
{
//open db connection, execute stored procedure
}
catch
{
//log error
}
In case we get any exception from stored procedure OR in opening database connection, we get an exception but we are not doing anything except for logging these errors. We don't have very critical data-storage/retrieval requirement. We are logging error just to be alerted and fix it later. Is this correct to put catch in every such function?
Using try and catch is not for logging purposes only, especially when dealing with database connections.
An exception means that something wasn't completed. If something wasn't completed, your business process failed. If your business process failed, you need to know about it and handle it within the scope of that code, not application_error. Each error should be handled within the scope it was generated from. application_error should be your last fallback, and theoretically should never be reached.
Sure, you can use it for logging, but also for closing your DB connection (which was probably opened before the exception occurred and be left forever open), informing your users that an exception occured, and for data recovery, alternating your process to deal with the exception or preparing it for a retry.
So, taking your posted template, good code handling should look like this:
try
{
//open db connection, execute stored procedure
}
catch
{
// Inform the user
// Alternate your process or preparing for retry
// log error
}
finally
{
// Close the DB connection
}
One should use try/catch blocks only in places where you can meaningfully handle an exception. However, "meaningful handling " includes providing good error messages.
If your catch block simply logs the exception with no additional context, then such block could be replaced with a top-level handler (like application_error) that does the same thing.
If, however, you log additional information available only at the point of invocation, then having a catch block is entirely justified: it enhances the experience by providing better diagnostics, which is a perfectly legitimate goal.

a method call and avoid the dll not found error all the time if exists

This method below is called when you click save all button.
I want to ask you is there any way to skip the error under the code shown below.
Why I ask this: Some times the pDenemeProxy.dll does not exist in the folder of the code.
Morever it is a windows form application. Has the pDenemeProxy.dll in the references. And the fDenemeProxy facade of pDenemeProxy.dll is only initialized if the mDesTemp not null.
Thank you!
private bool SaveAll()
{
...
..
..
if (this.mDesTemp != null)
{
fDenemeProxy dnm = new fDenemeProxy();
dnm.SaveThisCustomer(1234,"D",true);
}
...
..
return;
}
Error: System.IO.FileNotFoundException: 'pDenemeProxy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
note: .net 2.0 and c#
note: Some people advice to put try catch block but it did not work. I have seen during the debug sessions on VS 2008 that when mDesTemp is null we see again the error declared above.
In some line in your code you are using a method which throws an Exception of type System.IO.FileNotFoundException if the conditions for this erroneous situation are true (i.e. you are trying to access a file which is not possible for some reason).
That's the intended and correct behavior what you are experiencing. Whenever you are getting this error message the error has already been happened and now it's up to you to deal with this new situation. That is what Exception-Handling is all about.
To deal with an error that was caused by an exception (informally speaking) you would have to catch a exception that has been thrown before (formally speaking).
To do that you have to enclose the portion of code (the actual method call that inheres the throwing of the exception) with a so-called try-catch block like this:
private bool SaveAll()
{
...
..
..
if (this.mDesTemp != null)
{
try {
fDenemeProxy dnm = new fDenemeProxy();
dnm.SaveThisCustomer(1234,"D",true);
} catch (FileNotFoundException e) {
// deal with the new situation !
}
}
...
..
return;
}
The meaning of that is very simple and intuitive:
Inside the try-block you are 'securing' a piece of code that is capable of throwing an exception for the case it is doing so. This try - block is then followed by an arbitrary number of catch-block - one for each exception that could be thrown by the secured code.
If you have set up this try-catch block correctly you have achieved that whenever your (secured) code throws an exception the execution flow of your program doesn't end (i.e. you program doesn't crash) but it goes to the aproprirate catch-block where you can do anything to deal with error you have just experienced.
Furthermore if you would look on the internet you will find lots of information on that since exception-handling is a very important concept of programming but what I've tried to explain here is the basic concept which you should try to understand first - it won't get more difficult ;)

Annotating Exceptions with extra information without catching them

Exceptions sometimes occur. When they do, they're logged and later analyzed. The log obviously contains the stack-trace and other global information, but often crucial context is missing. I'd like to annotate an exception with this extra information to facilitate post-mortem debugging.
I don't want to try{...}catch{... throw;} since that counts as catching an exception and that makes debugging harder (during development I'd like the app to stop and the debugger to react when the original exception is thrown, and not when the outermost uncaught exception is). First-chance exception handlers aren't a workaround since there are unfortunately too many false positives.
I'd like to avoid excessive overhead in the normal, non-exceptional case.
Is there any way to store key pieces of context (e.g. filename being processed or whatever) in an exception in a way that doesn't catch the exception?
I am taking a shot at this building off of Adam's suggestion of Aop. my solution would be Unity rather than postsharp and the only question I would have is whether the exception is being caught inside of invoke, which it likely is...
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
//execute
var methodReturn = getNext().Invoke(input, getNext);
//things to do after execution
if (methodReturn.Exception != null)
methodReturn.Exception.Data.Add("filename", "name of file");
return methodReturn;
}
}
There is nothing wrong with the following pattern:
try
{
// Do Something
}
catch (GeneralException ex)
{
throw new SpecificException(
String.Format("More specifics ({0}) in message", someData),
moreContext,
new {even, more, context},
ex);
}
This is precisely the pattern to use, for instance, when the "Do Something" is to, say, open a file of some kind. The "SpecificException" might be "can't read configuration file".
I would not use AOP to catch the exceptions. Instead I would use the interception class to LOG the exception + all arguments to the method that threw the exception. And then let the original exception be thrown again

How to log exceptions in Windows Forms Application

I read a lot about how bad catching base Exceptions is and I have to confess that I did it also:
try{
...
}
catch (Exception exception){
MessageBox.Show(exception.Message, "Error!");
MyLogger.Log(exception.Message);
}
Now I would like to do it right and have some questions about it:
Which exceptions should I catch (for example FileNotExists for file manipulation, but what for TableAdapter or ReportClass (CrystalReports))
Where can I see a list of exceptions, that an objects can throw (for example TableAdapter)
Where in Windows Forms Application can I set a static method, which will log any exception to a file for example
Any other suggestions?
Catch whichever exceptions you can reasonably handle. For example, if you're trying to open a file for writing, you should expect that maybe the file is marked read-only, so that would throw an exception. But in the same situation you wouldn't try to catch a null argument exception, because that would be due to programmer error.
They should be found in the function reference in MSDN (you'll have to look it up on each one). For user-defined functions, you'll have to go digging, unless there is additional documentation or summary commentary.
3, 4. Consider using a logging library for .NET
I have one thing to add. If you just want to log an exception without affecting program flow you can always do this:
try
{
...
}
catch (Exception exception)
{
MyLogger.Log(exception.Message);
throw;
}
That's up to you to decide which exceptions your application logic can reasonably expect to recover from.
Exceptions are thrown by method invocations, not objects. In Visual Studio, Intellisense explanations will tell you which exceptions are thrown by an object (provided that the XML documentation describes which exceptions a method throws.
Rather than use a static method, respond to the Application.ThreadException event. The link provided has examples.
MSDN
You can set an event for unhandled exceptions in application events file
(got a VB sample here but i hope you get the point)
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
End Sub
You can find the application events in the options of you project.
You should only catch exceptions you can do something about, really.
That's the rule of thumb. I typically have a try/catch around my Program.Main just in case an exception bubbles right to the top and needs logging. You can also handle the CurrentDomain_UnhandledException event, in case exceptions are thrown in other threads than the UI thread (assuming you are multithreading).
In response to "4. Any other suggestions?":
In your example code, a message box is displayed before logging the exception. I would recommend logging the exception before displaying the message, just in case the user sees the error message, panics, and goes on vacation without clicking "OK". It's a minor thing, but message boxes block the program indefinitely and should be used with discretion!

How can I handle an exception in DataSet.Designer.cs?

I'm using Visual Studio 2008 along with C# to access a MySql database. To this point I have relied on Visual Studio to create the code for the DataSet, and that seems to have given me a problem. If the database is inaccessible (i.e. not running) it gives a "MySqlException was unhandled", "unable to connect to any of the specified MySQL hosts".
My question is what is the best way to handle this exception?
I would like to be able to handle it without tampering with the designer.cs file, but if that is not possible then any way of solving this will do.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)]
public virtual int Fill(customerDataSet.addressesDataTable dataTable) {
this.Adapter.SelectCommand = this.CommandCollection[0];
if ((this.ClearBeforeFill == true)) {
dataTable.Clear();
}
// Exception occurs on the line below.
int returnValue = this.Adapter.Fill(dataTable);
return returnValue;
}
When handling exceptions, you should catch the exception at the earliest moment you have something you want to do in response to the exception. A DataSet is a poor place to handle the event of your database being inaccessible; how will the rest of your application be notified that this error has occured?
In your case, how do you wish to handle this MySqlException being thrown? In most cases, an inaccessible database is going to be a difficult error to recover from. You may wish to let the exception bubble up through your current process and simply display an error message, or you might want to re-attempt the process, or you may wish to switch to another database.
It sounds to me that you might want to do some general reading around the purpose of exceptions and why the "throw" mechanism exists. They're not simply there to annoy you into writing try-catch blocks!

Categories

Resources