I have a third party library that sometimes causes the AccessViolationException. I've marked the culprit line. I'd really like this method to fail gracefully so that my calling code can try it again in a short time, but at the moment, this exception brings down the whole application.
public static PlayerModel GetModel(int instanceId)
{
try
{
// New player model.
PlayerModel model = new PlayerModel();
// Fill.
model._flakyLibrary = new FlakyLibrary(instanceId); // **Sometimes crashes**
model.instanceId = instanceId;
// Return the new player model.
return model;
}
catch
{
// Try again in a bit - the game is not fully loaded.
return null;
}
}
One thought I had was to start a child process to run this bit of logic and have that crash gracefully if it needs to - I don't know how to do this, let alone have one process return this kind of object (my custom PlayerModel) to another process. I have exhausted searching Google and Stack Overflow (maybe I'm asking the wrong questions?).
Solution
Huge thanks to Theodoros. I've added the following attributes to the above method. The exception is now being caught.
[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
[System.Security.SecurityCritical]
P.S - I'm still fascinated to know about the multiple process solution if anyone knows what I should be researching? Many thanks again.
Another edit:
I found a solution to using multiple processes: NamedPipeServerStream.
An AccessViolationException is an exception typically raised when your process tries to access memory that's not its own. (Incidentally, a NullReferenceException is just an AccessViolationException at low addresses, served with a different name, to give you a hint as to what caused it.) Thus, it's reasonable to say that this is more or less what happens inside your program: a dereference of an invalid pointer (possibly a null pointer) or access beyond the boundaries of a particular buffer.
If you're not messing with pointers, your code is not responsible for the problem. The constructor you are invoking is responsible for doing something unsafe and invalid. If the library you're using is open source, you can go in and try to diagnose the problem yourself, by looking for suspicious behaviors like those described above. You can then go ahead and try to fix it (and possibly contribute your fix to the developers of that library).
If the above can't be done for any reason, there is a workaround. By default, managed code cannot catch an AccessViolationException, because it's a Corrupted State Exception (CSE), but you can opt-in to handling such exceptions either globally (by applying a fix described in another answer) or per method (by using the [HandleProcessCorruptedStateExceptions] attribute).
However, you'll have to understand the risks taken: your program will be attempting to recover from corrupted state. If you can, try not to use a library that forces you to do that at all.
Related
I have a specific process I am running... there can be many errors during it as it uses player input, and the errors can be found in various classes because it's big. For clarification, I am building a parser(using antlr4), and many syntax and language errors can happen anywhere in the code because of that(Not actual exceptions, just them writing bad code in my language). I'd like it so that when such an "error" is detected, The entire parsing process would stop but without throwing an exception...
Ik that I can wrap a Try-Catch around the whole process easily and then just use that... but considering how big that is and knowing that it's not recommended to put a Try-Catch on really big stuff unless really necessary, I wonder if there's another way to force the entire callstack to back off.
So far, I have a static property IsRunning on a Diagnostic class, and whenever you use the Diagnostics.PrintError() method IsRunning is set to false. But for things to actually stop I need to throw ing if (!Diagnostics.IsRunning) return null; practically after every invoke to a method that might call Diagnostics.PrintError()... and not only is it quite dumb and hard to maintain... it's extremely easy to miss a check like that and never find out where it comes from...
Does anyone have a better solution or will I be forced to use C# Exceptions and a HUGE Try-Catch around the whole process?
as a reminder, what I want is to be able to completely force-stop the entire parsing process if a certain condition is met(in my case, !Diagnostics.IsRunning), but still, continue everything else, essentially popping the entire callstack up to the point that the Parse() method was called, and continue normally from there.
I'm new in a developement for Windows 8 and C#, but I have certain experience with Java Programming.
So, when I try to make some Json parser (for example) in java, I can't do it without use a try - catch block, and this way I can handle the exception, but when I try to do the same in c# (Windows 8) and I don't use the try - catch block it works too, like this:
if (json != null)
{
JObject jObject = JObject.Parse(json);
JArray jArrayUsers = (JArray)jObject["users"];
foreach (JObject obj in jArrayUsers)
{
ListViewMainViewModel user = new ListViewMainViewModel(
(String)obj["email"],
(String)obj["token"],
(String)obj["institution"],
(String)obj["uuidInstitution"]);
usersList.Add(user);
}
return usersList;
}
}
As I know the right way is to catch JsonReaderException, but Visual Studio never warned me on that. I would like to know if there's a easy way to know if some method throw an exception, like is on java using eclipse (it's mandatory implement try-catch block or code wont compile)
You will have to consult the documentation for that. C# lacks a throws keyword.
The term for what you are looking for is checked exceptions, and more info can be found in the C# FAQ.
In C# you are responsible for handling exceptions - which IMHO is the better way of going about it than the Java implementation. In effect, an exception should be, well exceptional, that is: It isn't something you should just always expect to happen.
Consider this weirding (yet, common) anti-pattern:
try {
} catch (Exception ex) { /* Handler goes here */ }
What exactly does that mean? Are you really going to handle every single exception that passes through here? Even stuff like OutOfMemoryExceptions? That's nuts. The only thing this sort of pattern will lead to is suppressing legitimate exceptions that really ought to bring down the application - this is fairly similar to the Java approach.
Think of an Exception as being a flag to the programmer that says 'hey, the environment just entered an impossible state'. For example, if I try to divide by zero and the system throws a DivideByZeroException, then rightly the system should alert you to this, because this is a failure - one the system can't just 'figure it's way out of' - and if you simply suppress the issue, how is that really helping? In the end this is counter-productive, in that all you're doing is masking over what is really an impossible application state. If you do this a lot in your application, then it eventually just devolves into a sludge of toxic wrong-ness. Yuck!
Exceptions also take up a lot of screen real estate. Sometimes I wish they would make the try/catch/finally blocks a little more streamlined, but then I remember that doing so would encourage people to use them more, so I repent of that position pretty quick.
Exceptions are useful programmer-to-programmer notifications saying that something you're doing doesn't make sense. Obviously we should never pass raw exceptions to the user because they won't know what to do with them. At the same time, you don't want to try to handle every single exception on the face of the earth, because 'handling' in this sense typically transforms into 'suppression', which is way worse than just letting the application fail (gracefully).
C#, as has been mentioned, does not have checked exceptions, and thank goodness.
The idea of checked exceptions sounds great on its face, but talk to anyone who is forced to use them by language or runtime, and they'll say there are three big problems with checked exceptions:
They impose their will upon the consuming coder. Checked exceptions, by their definition, are expected to be handled before they are thrown out of the runtime. The runtime is in effect telling the coder "you should know what to do when I throw this, so do so". First off, think about it; you are told to expect something that happens in exceptional cases by its very definition. Second, you're expected to somehow handle it. Well, that's all well and good when you actually have the ability to address the problem the exception indicates. Unfortunately, we don't always have that ability, nor do we always want to do everything we should. If I'm writing a simple form applet that performs a data transformation, and I just want my application to die a fiery death if there's any problem, I can't just not catch anything; I have to go up all possible call stacks of every method that could throw something and add what it could throw to the throws clause (or be extremely lazy and put a "throws Exception" clause on every method of my codebase). Similarly, if my app is constructed such that I can't throw out a particular exception, perhaps because I'm implementing an interface beyond my control that doesn't specify it as a potential throwable, then my only options are to swallow it entirely and return a possibly invalid result to my callers, or to wrap the exception in an unchecked throwable type like a RuntimeException and throw it out that way (ignoring the entire checked exception mechanism, which is not recommended of course).
They violate SOLID, especially the Open-Closed Principle. Make a change that adds a checked exception to your code, and if you can't handle said exception, all usages of your method must either handle it or mark themselves as throwing the exception. Usages which rethrow must be handled by their own callers or they have to be marked as throwing the same exception. By making a change as surgical as calling an alternate method in a particular line of code, you now have to trace up all possible call stacks and make other changes to code that was working just fine, just to tell them your code could conceivably throw an exception.
They create leaky abstractions by definition. A caller consuming a method with a "throws" clause must, in effect, know these implementation details about its dependency. It must then, if it is unwilling or unable to handle these errors, inform its own consumers about these errors. The problem is compounded when the method is part of an interface implementation; in order for the object to throw it, the interface must specify it as a throwable, even if not all of the implementations throw that exception.
Java mitigates this by having a multilevel hierarchy of Exception classes; all I/O-related exceptions are (supposed to be) IOExceptions, for instance, and an interface with methods that have IO-related purposes can specify that an IOException can be thrown, relieving it of the responsibility to specify each specific child IOException. This causes almost as many problems as it solves, however; there are dozens of IOExceptions, which can have very different causes and resolutions. So, you must interrogate each IOException that you catch at runtime to obtain its true type (and you get little or no help identifying the specific ones that could be thrown) in order to determine whether it's something you can handle automatically, and how.
EDIT: One more big problem:
They assume try-catch is the only way to handle a possible exception situation. Let's say you're in C# in an alternate universe where C# has Java-style checked exceptions. You want your method to open and read a file given a filename passed into it by the caller. Like a good little coder, you first validate that the file exists in a guard clause, using File.Exists (which will never throw an exception; in order to return true, the path must be valid, the file specified at the path must exist, and the executing user account must have at least read access to the folder and file). If File.Exists returns false, your method simply returns no data, and your callers know what to do (say this method opens a file containing optional config data, and if it doesn't exist, is blank or is corrupted, your program generates and uses a default configuration).
If the file exists, you then call File.Open. Well, File.Open can throw nine different types of exceptions. But none of them are likely to occur, because you already verified using File.Exists that the file can be opened read-only by the user running the program. The checked exception mechanism, however, wouldn't care; the method you're using specifies it can throw these exceptions, and therefore you must either handle them or specify that your own method can throw them, even though you may take every precaution to prevent it. The go-to answer would be to swallow them and return null (or to forget the guard clause and just catch and handle File.Open's exceptions), but that's the pattern you were trying to avoid with the guard clause in the first place.
None of this even considers the potential for evil. A developer might, for instance, catch and encapsulate an unchecked exception as a checked one (for instance, catching a NullPointerException and throwing an IOException), and now you have to catch (or specify that your method throws) an exception that isn't even a good representation of what's wrong.
As far as what to use instead in C#, the best practice is to use XML documentation comments to inform the immediate caller using your method that an exception could potentially be thrown from it. XML-doc is the .NET equivalent to JavaDoc comments, and is used in much the same way, but the syntax is different (three forward slashes followed by the comments surrounded with a system of XML tags). The tag for an exception is easy enough to specify. To efficiently document your codebase, I recommend GhostDoc. It will only generate exception comments for exceptions explicitly thrown from inside the method being documented, however, and you'll have to fill in some blanks.
I'm not a java developer, but from the answers here it seems as though the Java implementation is a burden to clients of those methods. However, C# missed an opportunity (Java-like or otherwise) to communicate to the caller the type of exceptional outcomes that could happen, as authored by the developer of the method, allowing me the caller to handle it appropriately.
Since this construct isn't built into the language, I would suggest to library developers that you adopt a wrapper class and use it as the return type for any methods that could go awry. Using said class as the return type in lieu of exceptions, clients can reason about what to expect when calling the method, as it is clearly defined in the method signature. Also, using the wrapper would allow a method to tell a client why something went awry in a way does not break the flow like exceptions do.
More on this subject here: http://enterprisecraftsmanship.com/2015/03/20/functional-c-handling-failures-input-errors/
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.
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).
What is Environment.FailFast?
How is it useful?
It is used to kill an application. It's a static method that will instantly kill an application without being caught by any exception blocks.
Environment.FastFail(String) can
actually be a great debugging tool.
For example, say you have an
application that is just downright
giving you some weird output. You have
no idea why. You know it's wrong, but
there are just no exceptions bubbling
to the surface to help you out. Well,
if you have access to Visual Studio
2005's Debug->Exceptions... menu item,
you can actually tell Visual Studio to
allow you to see those first chance
exceptions. If you don't have that,
however you can put
Environment.FastFail(String) in an
exception, and use deductive reasoning
and process of elimination to find out
where your problem in.
Reference
It also creates a dump and event viewer entry, which might be useful.
It's a way to immediately exit your application without throwing an exception.
Documentation is here.
Might be useful in some security or data-critical contexts.
Failfast can be used in situations where you might be endangering the user's data. Say in a database engine, when you detect a corruption of your internal data structures, the only sane course of action is to halt the process as quickly as possible, to avoid writing garbage to the database and risk corrupting it and lose the user's data. This is one possible scenario where failfast is useful.
Another use is to catch programmer errors. Say you are writing a library and some function accepts a pointer that cannot be null in any circumstance, that is, if it's null, you are clearly in presence of a programmer error. You can return an error like E_POINTER or throw some InvalidArgument exception and hope someone notices, but you'll get their attention better by failing fast :-)
Note that I'm not restricting the example to pointers, you can generalize to any parameter or condition that should never happen. Failing fast ultimately results in better quality apps, as many bugs no longer go unnoticed.
Finally, failing fast helps with capturing the state of the process as faithfully as possible (as a memory dump gets created), in particular when failing fast immediately upon detecting an unrecoverable error or a really unexpected condition.
If the process was allowed to continue, say the 'finally' clauses would run or the stack would be unwound, and things would get destroyed or disposed-of, before a memory dump is taken, then the state of the process might be altered in such as way that makes it much more difficult to diagnose the root cause of the problem.
It kills the application and even skips try/finally blocks.
From .NET Framework Design Guidelines on Exception Throwing:
✓ CONSIDER terminating the process by calling System.Environment.FailFast (.NET Framework 2.0 feature) instead of throwing an exception if your code encounters a situation where it is unsafe for further execution.
Joe Duffy discusses failing fast and the discipline to make it useful, here.
http://joeduffyblog.com/2014/10/13/if-youre-going-to-fail-do-it-fast/
Essentially, he's saying that for programming bugs - i.e. unexpected errors that are the fault of the programmer and not the programme user or other inputs or situations that can be reasonable expected to be bad - then deciding to always fail fast for unexpected errors has been seen to improve code quality.
I think since its an optional team decision and discipline, use of this API in C# is rare since in reality we're all mostly writing LoB apps for 12 people in HR or an online shop at best.
So for us, we'd maybe use this when we want deny the consumer of our API the opportunity of making any further moves.
An unhandled exception that is thrown (or rethrown) within a Task won't take effect until the Task is garbage-collected, at some perhaps-random time later.
This method lets you crash the process now -- see this answer.