I have a segment of code:
try
{
//sniping out a bunch of irrelevant code here
result = cmd.ExecuteScalar();
onExecution?.Invoke(result);
return true;
}
catch (SQLiteException e)
{
if (e.ResultCode == SQLiteErrorCode.Corrupt)
{
CorruptionDetected?.Invoke(null, EventArgs.Empty);
}
//snip - else if {etc}
throw;
}
The problem: I have VS to set to break on all exceptions always all the time no matter what without exception. VS does this correctly and without problem on every other exception everywhere in the program EXCEPT for this one.
I know WHY the error happening. That is of absolutely no interest to me whatsoever and is unrelated.
What I want to know is why that problem seems to either not actually generate the exception or else isn't catching it. I know with 100% certainty that errors are happening. You can see them in the Events tab in the Diagnostic Tools window. They pile up there but at no point do I ever get a catchable exception, just useless garbage in the Events tab.
How do I deal with this? If the error (SQLite error (5): database is locked) is a problem, then why am I not getting an exception? If it's not a problem and it's getting eventually processed, why is it polluting my Events list?
The way it currently stands is just utterly unacceptable as it makes absolutely no sense. Either it's a problem in which case I should get an exception or it's not a problem in which case I don't want to be inundated with useless debug events.
I've recently investigating the same problem in our C#/C++ code. I ended up downloading the System.Data.SQLite source code and debugging the library. System.Data.SQLite DLL is a C# wrapper around the standard SQLite (C++) library.
The most important: System.Data.SQLite DLL uses exceptions, however SQLite uses return codes. The wrapper intercepts return codes from SQLite and transforms them into exceptions, if reasonable.
If SQLite code (SQLite.Interop) was compiled with INTEROP_LOG flag, the library only logs certain errors to standard output and doesn't (maybe by mistake??) notify the wrapper about this kind of error. Therefore wrapper is unaware of the problem and won't throw an exception.
More in depth:
If you mangage to download and compile the System.Data.SQLite library on your own, try setting a break-point in file SQLite.Interop\interop.c in function sqlite3InteropLogCallback. Your program will stop whenever the 'database is locked' error is encountered, however no exception will be throw.
Related
I know Access Violation Exception is a serious problem that I should not really try to handle.
I also know that in the latest version of .Net, one can handle this exception by
put this <legacyCorruptedStateExceptionsPolicy enabled="true"> in the config and all the catch block would be able to catch the errors
Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute
Actually this made it very clear.
But my case is a little bit different and I cannot seem to find the solution:
I am using an unmanaged c++ library which I will initialise it at some point of my application. Then this dll itself will perform some tasks by itself(pulling data from server to cache, logging etc.) This Access Violation Exception looks to be thrown during this process, not when the appication directly call the dll's api. So I have no way to try catch the offending logic.
At this stage I have managed to catch it in AppDomain.CurrentDomain.UnhandledException like so:
[HandleProcessCorruptedStateExceptions, SecurityCritical]
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Logger.Error("Unhandle Exception", (Exception)e.ExceptionObject);
}
But I still cannot quite prevent the application from crashing.
I know I probably should just let the application crash. But I really believe this error is not as bad as it appears and I just need to know how to suppress it, even though I might not use it.
Any thoughts?
Access violation exception are a sign of something going seriously wrong, and needs fixing. Continuing running after such errors is not advised since you cannot be sure about the state of your processes, and may cause more serious errors further down the line if you try to continue. If this is thrown on a thread started by the third party code there is little you can do to catch it as far as I know. I'm not sure why you think it is not as bad as it appears, but I would be very careful trying to deal with it.
If it is in third party code that you do not have access to the best solution is probably to contact the author and have the issue fixed. The second best solution may be to run the third party code in a separate process. That way you can be sure that your process is not harmed if the code crashes.
I have created a C++ DLL and I am using it in a C# application. How should I report errors?
Use exceptions and throw my errors, or print them on std::cout or std::cerr, or something else? If I issue an exception inside my DLL, will my C# application be able to catch it? What is the best course of action on this regard?
Here's an example output from C# using PInvoke to call a method which throws std::exception.
ex = System.Runtime.InteropServices.SEHException (0x80004005):
External component has thrown an exception.
at ConsoleTester.Program.throw_exception()
at ConsoleTester.Program.Main(String[] args) in ConsoleTester.cs:line 18
Note: In this case throw_exception() is the exposed native method and it called a sub-method, but you can't see that part of the stack trace. All you get for deepest stack frame is the native boundary.
So, it isn't perfect, but it does work. Returning error codes is probably the most standard way to handle this, but if you're the only consumer of the library it probably won't make much difference.
Note: stdin/stdout is generally the worst way to handle errors. The exception being that it's not so bad to write a custom error handling object or set of routines that everything in the application can access when something goes wrong. (The output from such an interface might sometimes be stdin/stdout or a file or whatever is useful as configured) think log4j or log4net here...
Generally, logging is only part of error handling. You've still got to signal other parts of your application to respond to adverse conditions and (hopefully) recover from them. Here, only error codes or exceptions really work well (and exceptions are to be minimized from main program flow anyways).
Don't print errors on stdout or stderr! You need to return errors programatically so the C# application has a chance to handle them. What if the host application is a GUI app?
Throwing exceptions from a C++ DLL is fraught with peril. Even if your application was C++, it would have to be compiled with the exact same compiler as the DLL, like #ebyrob said. Calling from C#, I'm not sure.
Best course of action is returning error codes.
It really depends on how strong the error is. Most libraries that I've seen will return a success or failure result value from their function calls that you can check for manually in your code when you use it. They usually provide another method that just retrieves the error message in case you want to see it.
Save throw exceptions for the really big stuff that you can't continue without, this will force people using your library to fix those errors (or at the very least, see that there is a big problem).
I would not recommend printing anything in the console window, it is a very slow operation and having it in there forces anyone using your library to have that overhead with little option for optimization. If they want to print the error messages, they can just retrieve the error data from your library and print them out themselves.
Using C#'s System.Diagnostics.Process object, I start an unmanaged exe, that later starts yet another unmanaged exe.
The 2nd exe is causing an unhandled-exception that I'd like my application to ignore, but can't seem to.
I'm using a try/catch statement when I start the first process, but it doesn't seem to catch the exception raised by the 2nd process. When the exception occurs, the just-in-time debugger notifies me and halts my application until I manually click "yes" I want to debug or "no". Then my application proceeds.
The JIT debugger doesn't have source code for the 2ndprocess.exe that is throwing the exception. So, it doesn't tell me what the exception is. I don't really care what the exception is, I just want to know how to catch it and ignore it so my application doesn't get halted by it. By the time the exception occurs, the work is done anyway.
Can anyone offer some insight?
You should be properly handling the exception in the second executable. Your main program won't catch the exception because it isn't throwing one, it is executing something that is.
Edit:
Do you have access to the source of the second process (the one throwing the exception)? Your application shouldn't ever just crash. If the exceptional case gets handled correctly in the second process, you won't have this problem in your primary application.
Edit2:
Since you have access to the source (open source) I recommend you fix the bug. This will help you in two ways:
1) Your program will finally work.
2) You can say you contributed to an open source project.
And, as a special bonus, you get to help out a project you use frequently. Win/Win
Since you are using process.start to actually launch the application, the application creates a separate application domain. Capturing the exception from that application is not something that I believe will be possible, since more than likely the JIT dialog is coming up due to that failed process.
Although not a solution you could stop the dialog if needed, but that has issues of its own.
I have a rather simple C# program (no UI, just command line) that uses a 3rd party library (Abbyy's Finereader 8.1) to do some work and then exits.
Simple enough and works quite well. Recently however we've started getting the following error from the program:
Application Error : The instruction at
"0x2c0de46b" referenced memory at
"0x0732aa84".
A little digging shows that this is happening at the end of the C# code. Basically the last two lines are:
Console.WriteLine(message);
return statusCode;
The final console message is written and the output from the program is fine. Indeed, if it wasn't for the fact that this error keeps the program from fully terminating I could work around it.
We're running two scripts that invoke this program each on two machines. This happens at random (as far as I can tell) but usually at least one of (the 4 scripts) hits this each day. I thought that perhaps some kind of weirdness was happening for concurrent runs, but testing eliminated that.
Any thoughts on possible causes would be most welcome as I've run out of ideas.
Also if anyone knows of a way to have the program terminate when this happens, that would be useful.
"Application Error : The instruction at "0x2c0de46b" referenced memory at "0x0732aa84"."
This error implies memory corruption somewhere in your code, without the full code i cannot say more than this.
The place where the exception is risen is not important in this case of error. Try to take a look at your code, especially the code that calls the library.
Well... Troubleshooting dictates that I ask what changed, but I reckon you thought about that yourself. What version of the .NET framework are you using? What OS(es) does this problem occur on?
I belief that this exception is coming from some cleanup that the 3rd party library does. Did you contact their support? Can you try to explicitly unload the library and see if the error still occurs then?
Or... did you try adding an handler for unhandled exceptions? Might be worth a try...
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(
OnUnhandledException);
//some code here....
}
/// <summary>
/// Occurs when you have an unhandled exception
/// </summary>
public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//here's how you get the exception
Exception exception = (Exception)e.ExceptionObject;
//bail out in a tidy way and perform your logging
}
(example code by DoctaJonez)
Just throwing some things out there, since there doesn't seem to be a definite answer (yet).
I have a application with similar code (not written by me)
try
{
EnumerateSomeCoolHardwareDevice();
}
catch (Exception ex)
{
}
UPDATE - This is .NET C# & EnumerateSomeCoolHardwareDevice() is using SerialPort?
I know how bad this code is but it works like this for a reason!
My question thou: I can see that it crashes somewhere in the EnumerateSomeCoolHardwareDevice(); but it doesn't get caught by the Catch (...) - It just crashes with the send report dialog! This also currently only happen in the release build... Is their ANY reason why my exception will NOT be caught by the catch (...)?
My guess is that you're not getting an Exception in your language/framework but rather EnumerateSomeCoolHardwareDevice() does weird things that simply cause the OS to kill your process. Remember that hardware details are abstracted by frameworks like Java and .NET, so whenever you do something with hardware directly, you're probably relying on unmanaged resources ... and whatever goes wrong there can kill you, catch or not.
One possible reason would be if the EnumerateSomeCoolHardwareDevice() function uses threading. If an exception is thrown in a thread and isn't handled within it's thread then it can crash an application. This simple app can demonstrate what I mean:
public static void testThread()
{
throw new Exception("oh god it's broken");
}
static void Main(string[] args)
{
try
{
Thread thread = new Thread(testThread);
thread.Start();
Console.ReadKey(); //Just to make sure we don't get out of the try-catch too soon
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you run that the app will crash and burn rather than catching the exception as you might expect.
In .NET catch (Exception ex) will only catch .NET exceptions, not native exceptions.
This question (catching native exceptions in C#) may help.
Assuming .NET, if EnumerateSomeCoolHardwareDevice uses Win32 methods via PInvoke (to access the hardware) and an error occurs, most Native methods return an error code. If that error code is not handled, and another native method is called anyway (perhaps with empty out parameters from the failed call), a serious native error (such as bad memory access or something similar) can cause a straight program crash, no exception thrown.
Have you tried the attribute
assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)
That should wrap any non-.Net exceptions into System.Exception so it will be catched in your code.
If it is only happening on the production machine and not the dev machines then it could be down to DLL mismatches. Double check ALL the referenced DLLs and frameworks are the same version.
Secondly if the error is not being thrown by the EnumerateSomeCoolHardwareDevice() then it will crash the app as there is no way for the exception to get back up the stack (or thats my understanding of try/catches) in my experience this has happened to me before.
Lastly, the microsoft error report usually allows you to inspect what will be sent to MS, this should let you see where the error happened and why (assuming it has readable information within it).
Check the Event Viewer as the error should also be logged there, and normally provides an invaluable source of detail regarding the error and with a bit of digging through the error listed there you should be able to trace the fault.
If you are in .Net version 1.1 use a no parameters catch block like
catch{
...
}
Prior to .Net 2.0 there could be native exceptions that do not derive from System.Exception.
Also hook to appdomain unhandled exception event and see what happens.
There may be a try..catch inside EnumerateSomeCoolHardwareDevice().
If the exception is caught and handled there, the outer exception won't be hit unless the Exception is thrown again.
(Assuming Java) Both Error and Exception are subclasses of Throwable. If there is an assertion failing in EnumerateSomeCoolHardwareDevice() for example you will get an Error.
My guess is that there's a stack overflow happening. The .NET VM simply shuts down Release build processes that encounter a stack overflow, no CLR exceptions thrown. There's probably an internal try / catch inside that function that catches StackOverflowException one way or other, that's why it's not propagating to your code in Debug builds either.
The easiest way to figure out what's going on is by making a debug build, attaching a debugger and instructing the debugger to break before any exceptions are thrown (in Visual Studio, Debug/Exceptions and tick "Thrown" for "Common Language Runtime Exceptions" and possibly other ones as well, in cordbg.exe "catch exception")
If it is crashing madly and is using a SerialPort object then it is probably because at some point it skips onto a background thread and an exception happens here. IIRC the .DataReceived event or however you get information back from a serial port returns data on a background thread. Should an exception be thrown in this routine then the entire application will bail.
Find the background thread and put some exception handling round it.
What types of exception have you seen behaving in this way? Do you have a list of them?
Some exceptions will keep propgating up the call stack, even if they've been caught in a catch block, such as ThreadAbortException.
Others are essentially unhandleable, such as StackOverflowException or ExecutionEngineException.
If it is one of these (or some others I have probably missed), then the behaviour is probably as expected. If it is some others, then a deeper look with more information will be necessary.