C# Simulate the effect of throwing an exception without throwing an exception - c#

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.

Related

How to know if some method can throw an exception

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/

Try... Catch block infestation

I'm developing a suite of Excel add-ins for a company. I haven't done add-ins before, so I'm not terribly familiar with some of the intricacies. After delivering my first product, the user encountered errors that I didn't experience/encounter/notice during my testing. Additionally, I was having difficulty reproducing them from within Visual Studios debug environment.
I wound up writing a light weight logging class that received messages from various parts of the program. The program isn't huge, so it wasn't a whole lot of work. But what I did end up with was nearly every single line of code wrapped up in Try... Catch blocks so I could log things happening in the users environment.
I think I implemented it decently enough, I tried to avoid wrapping calls to other classes or modules and instead putting the block inside the call, so I could more accurately identify who was throwing, and I didn't swallow anything, I always threw the exception after I recorded the information I was interested in.
My question is, essentially, is this okay? Is there a better way to tackle this? Am I waaaay off base?
Quick Edit: Importantly, it did work. And I was able to nail down the bug and resolve it.
No, you are not way off base. I believe this is the only way to handle errors when writing Add-ins. I am selling an Outlook add-in myself which uses this pattern. A couple of notes though:
You only need to wrap the top-level methods, either exposed to the user interface directly or triggered by other events.
Make sure your logging routine traverses the Exception tree recursively, also logging InnerExceptions.
Instead of rethrowing the exception you might consider displaying some sort of error form instead.
And then a couple of comments to those notes:
I'm sure you understand this, but your comment "nearly every single line of code is wrapped(...)" made me want to underline this. But yes, all your code should eventually end up in a catch (System.Exception)-block so that you can log your Exception. I disagree completely with Greg saying this is "dangerous". What is dangerous is not handling your exceptions.
If you do this I don't think you need to "avoid wrapping calls to other classes and modules", if I understand you correctly. I have a published a convenient extension method GetAsString that allows me to log what I need at github.
In Outlook, if an Exception bubbles up to Outlook itself, your Add-in might get disabled or even crash Outlook if it happens on a background thread. Isn't it the same in Excel? Therefore I go to great lengths not to let any exception out of my application. Of course you need to make sure your application can continue running after this, or allow for a graceful shutdown.

Can I/Should I use exceptions to error check my program?

The main example here is copying a word document. I have these lines of code in my program:
try
{
File.Copy(docTemplatePath, docOutputPath, true);
}
catch (IOException e)
{
MessageBox.Show(e.ToString());
}
Now I'm trying to build in error checks. I want to make sure that the output Word Document is not open elsewhere before I try to save, because otherwise an exception is thrown.
The way I see it is that the exception is thrown to warn me of an error that is causing the default functionality of the code to not work as expected. In this sense I would feel comfortable catching an exception, reading it to discern the issue (in this case that the document is currently locked/open elsewhere) and thus showing a MessageBox to alert the user to the fact the document they're trying to write to a file that is open elsewhere.
Is this fine to do? I have seen many places over the course of my looking into this where it would seem that this is what exceptions are designed to do, and other places where people seem to think thaat using exception to do stuff like this is hideously against all programming traditions and would prefer to check themselves.
What is the overall consensus?
Thanks
You should use Exceptions to handle exceptional occurrences.
That is; sometimes there will be foreseeable circumstances: A file name entered by a user might not exist, so your code should check File.Exists() before attempting to load it, for example (not relying on an exception).
That file already being in use and locked by something else might be an exceptional situation; it probably is, so that's probably just fine.
IMO, in .Net, exceptions should be used for managed unexpected errors.
For me it's a bad idea to throw an exception for a authentification error (like bad password) but it's a good to use it for manage a database connection error.
So, in few words, i use exceptions in order to manage unexpectable issues and not business issues. The idea of doing every business issues with an exception is more an "over" object oriented approach and is not what it should be use for.
Your example is IMO a good example of the good way to use exception.
Globally it's just a "big" try/catch around functionnality or specific tasks.
AFAIK Exceptions are designed for handling things that are out of the developers control like a hardware failure or disconnected network or something similar to that, where the developer might not have the knowledge of the problem,
IMHO it is better to check for the value of divider in the expression
int r = val/divider; than to check for the DivideByZeroException
Using Exceptions to control program flow is 'not done'. They should be used only to handle exceptional circumstances, when you don't want your entire application to crash.
That said, sometime it is necessary to use Exceptions. I believe the int.TryParse and other TryParse methods in the .NET Framework use Exceptions, catch them if it doesn't work, and then return false.
If there is no other way of knowing if a Word file is already open, my opinion is that you could use an Exception to do this. The good thing is that you catch a specific exception, because other things could go wrong. The problem is that the IOException could have another source (i.e. the destination folder is not accesible, etc.). This is true not only for your example, but for all (complex) exception-driven flows. The TryParse example I gave above is fairly simple, so there, it's not so much of a problem.
Conclusion: don't do it, unless it's the only way you can. And then, try to isolate it in a separate method. This way, if you find a better solution, you can always change your implementation. Also, try to catch the most specific exception, and keep in mind that exception can have several sources.
If a routine can satisfy its contract by returning normally, it should do so. If there is no way a routine can return normally without violating its contract, it should throw an exception. If a routine's contract is taken as a given, there's really not much room for judgment in deciding whether the routine should throw an exception. It should return or throw based upon the above simple rule.
The place judgment enters into the equation is in deciding what a routine's contract should be. A useful pattern is to provide both a "Try" version of a routine and a "Do" version; if the "Try" version is unable to perform the requested action because of a reasonably-anticipated problem, it will indicate that by returning some type of error value; if a "Do" version is unable to perform the requested action, for any reason, it will throw an exception.
As a simple example, consider "Integer.TryParse" and "Integer.Parse". If one has a string which may or may not be a valid number, one may call Integer.TryParse. Integer.TryParse will use a returned flag to indicate whether the parse was successful; it will return perfectly happily whether the parse succeeded or not, and the caller is responsible for ensuring that TryParse succeeded before trying to use the returned value. By contrast, Integer.Parse will only return if the number was parsed successfully. If the number wasn't valid, Integer.Parse will throw an exception. Calling code may thus use the value returned by Integer.Parse without having to check whether it succeeded; if Integer.Parse didn't succeed, it wouldn't have returned. Note that it's possible for Integer.TryParse to throw exceptions in some truly exceptional cases (e.g. if unsafe code had made the passed-in String reference point to some other type of object); the only guarantee is that it won't throw in the reasonably-expected cases (e.g. it's passed a string like "XYZ" instead of one like "123").
A slight enhancement to the Try/Do pattern is to have a routine accept a delegate which will be invoked if something goes wrong. In many cases, passing a delegate would be overkill, and it's often hard to decide in advance what parameters the delegate should take, but this approach can be advantageous in cases where a decision of whether to muddle on or give up may be determined by outside factors. Such situations arise in communications scenarios, where a program's proper response to a communications hiccup may be to up a message notifying the user that the program is having difficulty and allow the user to hit "cancel", but to have the program retry the operation a few times if the user does not. If the operation that had to be retried was a small portion of the overall operation to be performed, throwing an exception out to the main line would 'permanently' give up on the larger operation, while performing retries without user interaction could force a user to sit annoyingly long for the computer to give up on an operation the user might know won't possibly succeed (e.g. because the battery just died on the device he was communicating with). Using a callback delegate allows the optimal user interface experience, without tying the communications code to any particular user-interface implementation.

How to handle non-fatal error conditions

I'm not sure if this is a duplicate but if it is please feel free to close this.
Background:
I have a timer component for a game i'm writing that supports Stop and Pause methods. The non-critical error cases in question are doing things like calling Pause when in the timer is already paused, this is not fatal but it's not going to cause the change in state implied by the method name
Questions:
1. How does one generally indicate a non-fatal but abnormal condition?
2. Should I actually be throwing an exception in these cases? I think it's a little heavy-handed considering calling Pause when paused wont do any harm
3. Am I over-thinking this
UPDATE:
Based on the responses and comments here is the statergy I have chosen to take:
In development builds an exception will occur because I consider these bugs and I'd like to catch them and correct them. I can't justify an exception in a release build because these bugs don't corrupt the game state, and I don't think users of the application would appreciate the loss of their hard earned score because I failed to code properly
Thanks for all your responses, this has been very educational for me.
I think your fine to just ignore the call if the timer is already paused. Assuming the method is called Pause() then the client only requires that after the method call that the timer is paused, and exceptions should only be thrown if it won't be; the method doesn't imply any requirement on the current state of the timer.
On the other hand if the method was called ChangeTimerFromRunningToPaused() then that implies that it is only valid to call this on a running timer. Under these circumstances I would expect it to throw an exception informing the client that the timer is not in a valid state to process this method call.
Against the other answers, I would consider throwing an exception. If it would be my code performing the second Pause() call, I might consider my code to be broken if it makes this call where it should not. Maybe I am missing a check like if (Timer.IsRunning) { } and I don't want to hide this bug by silently ignoring the call. Even if the call is triggered by user input - a button click for example - this might be an indication of bad design and I should have a look at it. Maybe the button should be disabled.
The more I think about it, the less situations come to mind where the second call should not be an exception indicating bad calling code. So, yes, I would throw the exception.
UPDATE
In a comment Martin Harris suggest using Debug.Assert() to get the bug during development. I think that this is to weak because you won't get the bug in production code. But of course you don't want to crash an application in production because of this non-fatal error. So we will just catch this exception up the stack and generate a error report and than resume as if nothing happend.
Here are two goo links.
API Design Myth: Exceptions are for "Exceptional Errors"
Coding Horror - Exception-Driven Development
In such cases (moving some state machine to a state on which it already is), I'd just skip the call. Usually, non-fatal errors or warnings should not be thrown as exception, but rather returned as result (which can be ignored or processed, whatever fits the situation best).
No, don't throw an exception, Exceptions are heavy. There's nothing wrong to pause again. I don't see any harm.
This looks similar (though not identical) to one of my questions, perhaps the answers there are helpful for you.

What is Environment.FailFast?

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.

Categories