I have a WinForms application which dynamically loads an assembly generated by MatLab (3rd Party). Currently, I encountered the problem that an error (maybe exception) somewhere in the MatLab code structure, cannot be caught on C# side. And by this, the whole application goes down...
What I tried is:
Try/Catch Block (even with no exception type, as described here: https://stackoverflow.com/a/150675/3809520)
HandleProcessCorruptedStateExceptions attribute, as described here: https://stackoverflow.com/a/10517244/3809520)
Is there anything that I could do more?
Thanks!
Edit:
Application is using .NET 4.5 Framework
Edit2:
Tried Application.ThreadException event together with Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) and AppDomain.UnhandledExceptions event as proposed in comment - both events not triggered.
Edit3:
I will try to nail it down to a minimal example, the questions was intended to be more generic, like: what else can be done on my code side to catch exceptions
Related
Is is possible to know if a certain exception can be thrown inside a code block?
The premise: Assume you are working on some old codebase and you have something like this.
try{
a lot of code that calls a bunch of other methods
}
catch (CustomException e){
some handling
}
I want to know what code in the try block that can throw this exception. For all I know nothing is throwing it anymore and this is just dead code. I know this is caused by bad code design, but when working with real code it is not always possible to prioritize refactoring all of the old code.
So in short, is it possible to tell at compile time if anything in the try block actually throws that exception?
(if it matters I am coding in idea rider)
Edit: stackoverflow thinks this question already has an aswer to this question, but in reality that question does not have a good answer to anything.Question
No there is no automatic technique
Yes there is a manual techniques: You look at the definition of the reference: for .net component you see in comment the input args, return and exceptions susceptible to trigger, but this is manual approach that must be done on all targeted methods.
If your target code has undefined behavior, I suggest that you enhance your exception handling on time, and start with most generic exception in your first version.
You log the content of exception analyse what is it then add this new type of exception in your error handling.
in all the case if you let general exception in the end of catch you will catch everything and this is a current practice.
While your answer describes a method to handle the situation, it is not really an answer to the question. – Fildor
Yes it is an answer, do you know an automatic technique to list all Exceptions that can be triggered on a target code ?
But in existing code it might be pretty dangerous to remove a catch block that handles a specific exception in a specific way. – Chippen
Where do I suggest tor Remove a catch block ? If your target code already catches an exception, your caller code is not impacted by it as it will not see any exception, and there is no use to do this.
If however you see explicitly in the target code that an exception is triggered with static code analysis, and if you want to see how to trigger it, you can design a unit test and create a scenario with special input to specifically trigger the code path, and to expect the exception in the test definition.
In fact there is a problem of understanding between your question and my answer.
You want to ask.:
For a given exception type, is there a way to know that a given target code can throw this exception. Answer is you must analyse it manually or try to fuzz.
My initial answer target another question which would be: for a given target code is it possible to know all exceptions that could be triggered.
I'm developing an application with C#.NET 4.6
It references an old OCX LAPI.ocx
When this OCX receives some special message called PCPCM entire application crashes with HEAP Corruption exception.
Unfortunately I can't catch or handle that exception in my application.
Yesterday I tried my application with x32dbg. And it worked. x32dbg can catch exceptions and ignores them. How it can ignore such an exception? How I can do this in my application to prevent a crash?
UPDATE: I used dbg to find the point that the ocx raises an exception and tried to jump over it(and patched the original ocx). I put it under test. Hope it works.
UPDATE 2: I couldn't find a way to ignore or catch such exceptions. I couldn't make AddVectoredExceptionHandler working. But downgrading application to .NET 4.0 solved the original problem(No more exception and application crashed message).
Using .NET 4.0 I solved the problem entirely. See UPDATE 2.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Exception handling problem in release mode
I suspect there is a perfectly simple explanation for this, but I can't seem to find it.
When my WinForms C# 4.0 application loads itself in the Program.cs file, the entire Main() function has inside it a try/catch statement.
I have written a little exception wrapper which behaves quite similarly to the vanilla .net "uncaught exception" box, except it provides a bit more information, allows the exception tree to be saved (serialised), and it allows the user to submit the error report directly to me.
Now, it works fine while debugging (F5). If I trigger an exception anywhere in the program which is in the main thread, if there is not try/catch then the exception fires its way all the way back to Main() and shows the custom window.
(All other exceptions I have accounted for and are handled appropriately).
When I run the program simply by running the .exe file, the vanilla .net exception box comes up, not the one I have coded.
Is there any reason you can think of why this would happen?
The strangest thing is that it behaves quite differently when running in debug mode vs running on its own.
I am building as debug - not release.
Edit (22-March-11):
I'm just adding a little addendum here, in case some of you can't find the answer hidden in the comments for the accepted answer below:
Forget that I said I was building as debug instead of release. That is of no relevance - I just added it for extra info. What is important is that when I'm debugging in VS the exceptions are caught as expected, but when executing my EXE outside VS they aren't.
As Cody said, Application.Run() has its own handler for exceptions which is why they never get to my main catch, however I mentioned that I am not even using Application.Run() anywhere in my code... instead my GUI is first launched with Form.ShowDialog().
I have done some experimentation, and can confirm that Form.ShowDialog() behaves the same was as Application.Run() in that exceptions are handled within the method itself.
This is the expected behavior.
The difference you see is a result of the application being run with the debugger attached. When you launch it from within Visual Studio, the debugger is automatically attached (unless, of course, you choose to "Start Without Debugging"). That disables the built-in exception handler, which is the one responsible for showing you the "vanilla" .NET exception dialog. Launching it from outside VS doesn't attach the debugger, leaving the built-in exception handling enabled. (Note that this has nothing to do with compiling your program in "Debug" mode versus "Release" mode.)
See the accepted answer to this related question for more information. I do not believe the difference between VB.NET and C# is relevant in this case.
As that answer mentions, there is a way to disable the built-in exception handler. But before choosing to do so, I recommend reconsidering your approach. Rather than wrapping your entire Main method in a try-catch block, which sounds like a bit of a code smell to me, you might consider handling the built-in AppDomain.UnhandledException event. Jeff Atwood posted a great article here on Code Project about how to replace the standard .NET exception handling with your own more user-friendly method. The solution he proposes has become only that much more elegant as later versions of the .NET FW have improved how the AppDomain.UnhandledException event is handled.
I'm having a problem with an application hanging and giving me the default "Please tell Microsoft about this problem" popup, instead of the "unhandled exception" dialog in the application.
In the application code, the Application.ThreadException and AppDomain.CurrentDomain.UnhandledException are both redirected to a method which writes an error log to disk, saves a screenshot to disk, and shows a friendly dialog box.
But when this error occurs, none of those three things happen. All I get is this in the event viewer:
EventType clr20e3, P1 myapp.exe, P2 4.0.0.0, P3 47d794d4, P4 mscorlib, P5 2.0.0.0, P6 471ebc5b, P7 15e5, P8 27, P9 system.argumentoutofrange, P10 NIL
Given that the error only seems to happen after the application has been running for several hours, I wonder if it may be a memory-leak problem. I've searched a bit for "clr20e3" but only managed to find ASP.Net stuff. My application is Windows Forms (.Net 2.0) exe, using quite a few assemblies - in both C# and some unmanaged C++.
I guess that it could also be an error in the error handling method - As some answers suggest, I may try logging at the start of error handler (but given that that is pretty much what I do anyway...).
Any help solving this problem would be much appreciated - whether it is solutions, or suggestions in how to find out what the root cause of the problem is.
UPDATE: The root cause of the original bug was accessing an array with a negative index (that was the system.argumentoutofrange). Why this was not trapped is a bit of a mystery to me, but given than both exceptions were sent to the same handling code, I wonder if there may not have been a condition where (for example) both were invoked and fought over a resource (the log file, for example)?
I managed to prove this much by doing an EventLog.WriteEntry before anything else in the error handling code. Having now added a flag to prevent re-entry in the error handling, I no longer appear to have a problem...
Just shooting in the dark here - is it possible that the ArgumentOutOfRangeException is actually thrown from your exception handler?
Additionally, you didn't say what type of application is in question -- Application.ThreadException only affects WinForms threads, so if this isn't a GUI application it's useless. (See the remarks section in the MSDN documentation)
Have you checked whether the ArgumentOutOfRangeException is thrown from your handler itself? May be worthwhile doing a simple write to the event log or trace at the entry of your exception handler and confirm you're actually hitting it.
Edit: Information to writing to the event log can be found at:
http://support.microsoft.com/kb/307024
Are you calling Application.Run() more than once? This will exhibit the same symptons you describe. You must write a custom ApplicationContext class as a work-around. Just my $0.02 adjusted for inflation.