Is there a free alternative to Exception hunter? - c#

I'm switching back and forth between Java and C# and one thing I miss while I'm coding in C# is the enforced exception checking (Although I admit I also find it really irritating sometimes while I'm coding in Java).
I'm aware that Exception Hunter can help you track down what exceptions a piece of code might throw but is there a free/cheaper alternative? I can't really justify £200 for this kind of software addon as it's only an annoyance rather than a major problem.

Yes. Run the free Microsoft Pex on your code. It will show all possible exceptions that can be thrown.

While I understand the enforced exceptions thing, I'm not sure how genuinely essential it is... for example, most interesting exceptions are those that you wouldn't normally include (or even expect). For example, I'm currently fighting what looks very much like a CLI bug in CF35, intermittently raising MethodMissingException from code that really does exist (emphasis: intermittently).
If you want to document your exceptions, use the ///<exception ... >...</exception> markup. For other thoughts on this theme, perhaps see Vexing Exceptions (I wonder if GhostDoc might help any?)

Get Exceptional website is one possibility. Basic idea is that you create software and all exceptions are sent to this site to your account where you can pick them up. Of course it doesn't read your code and see what exceptions are there.
I don't know if there is C# library yet but the API is not too hard.

Related

Are there any open source projects that implement the same functionality with and without exceptions?

I'm working on my thesis about the impact of using exceptions on code complexity. It would be really great if I had a few thousand LOC that use good old error handling and exceptions for the same functionality. I don't even know where to start googling. Any C#, Java, C++, D project would suffice. My best guess is a project that switched to exceptions at a given version. Any help is appreciated.
Considering that in both Java and C# exception handling is essential for pretty much the complete base libraries, I doubt it.
Java is pretty much completely out of the loop because without out parameters you have to resort to extremely strange constructs (eg you either always return Object arrays or implement classes with a return value + the value that should be returned,..).
In c# you could theoretically get around using exceptions and using error codes if you ignore the base library, but I still doubt anyone would want to program that way. For both languages it's just integrated way too much into the core concept.
So your best bet of the named languages would be C++, but then C++ exceptions have a whole lot of problems compared to more modern implementations - really no fun to use them. You may look around for eg Python programs, I could imagine someone programming python without exceptions.
Anyways it's extremely unlikely (independent of language; although C++ is probably the only one where I could imagine it at all) to find a project that changed from error codes to exception handling - after all that'd be pretty much a complete rewrite..
I don't think you will find such projects, even if some project switched at some time, they will still be very much different, so you would compare apples and oranges anyway. Thesis is not supposed to be based on anecdotal information, questionable testing, and unwarranted conclusions.
You can approach this topic from two angles. One is to discuss theoretical implications of two approaches of error handling and illustrate that with three-liners. Another, is to conduct a controlled experiment writing probably short (~1000 lines) some real-life scenario test case and analyse it, followed by discussion whether it would or wouldn't scale on larger systems. And of course, if you have time (at least couple years) and money (at least couple million $) to hire a group of experienced developers and provide them with large-scale problems, you can gather some valuable statistics.
Not sure it fits, but:
GTK+, the C library, uses error codes whereas gtkmm, its C++ wrapper, wraps them in exceptions. (Example: GTK+ g_thread_create() vs gtkmm Glib::Thread::create()) Both are object-oriented.

Is there a near-consensus guideline for log levels?

I've been influenced by the log levels that I and my teams have used at my last two companies. I'll share ours here but keep in mind this bit is subjective:
Fatal - Your app is going down.
Error - This operation or thread is crashing and burning. The app may be able to continue.
Warn - The current operation may be able to continue but an engineer needs to investigate something.
Info - Explain what your operation is doing.
Debug - Explanation of operations that may get pretty spammy (inner loops, etc).
Now, my objective question is whether there is a highly-agreed upon style defined in this regard. The answer may be no. But if there is such a standard, can you point a URL to it?
Also note that I don't really care what threshold is actually configured to log somewhere useful in a deployed / production environment. Rather, my question is restricted to guidelines that those of us who write code should use.
I'm putting a C# tag and Java tag on my question. It's possible we'd have different guidelines in these two camps but there are probably only cultural reasons that we'd differ, not conceptual reasons.
I'm not even sure that whether something is "highly-agreed" upon can be answered objectively.
The Log4j and Log4Net libraries certainly employ the level definitions that you've described. See this link.
Somebody might yet produce a counter-example of a library that uses a differently defined set of logging levels.
from SSCLI (.NET sources):
namespace System {
...
[Serializable]
internal enum LogLevel {
Trace = 0,
Status = 20,
Warning= 40,
Error = 50,
Panic = 100,
}
...
}
note the [warning] values) I rely on this variant of distribution. anyway it's Microsoft)
There's no "highly agreed upon" standard, style or advice that I'm aware of. But each of the mainstream logging subsystems for Java has a set of levels that correspond to the 5 that you have identified. Indeed, the levels are well enough aligned in practice that it is possible to "unify" logging using the SLF4J facade. (I guess that you could say that this makes the SLF4J levels a defacto preferred style for Java.)
I would add a couple of caveats:
Advice about what an engineer can and should do in response to a log event is out of scope in describing what log events mean.
The categories are necessarily subjective, but using language like "crash and burn" is going to lead to misunderstanding.
In practice, usage may well not be consistent with the defacto style; e.g. some logging systems allow you to use other (non-manifest) levels, and developers may log events at the "wrong" level.
Note that slf4j 1.4 added support for a TRACE level.
Thought I'd add the levels from the Python logging facility:
DEBUG - Detailed information, typically of interest only when diagnosing problems.
INFO - Confirmation that things are working as expected.
WARNING - An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR - Due to a more serious problem, the software has not been able to perform some function.
CRITICAL - A serious error, indicating that the program itself may be unable to continue running.
These can be found here:
http://docs.python.org/howto/logging.html#logging-basic-tutorial

When is it appropriate to use error codes?

In languages that support exception objects (Java, C#), when is it appropriate to use error codes? Is the use of error codes ever appropriate in typical enterprise applications?
Many well-known software systems employ error codes (and a corresponding error code reference). Some examples include operating systems (Windows), databases (Oracle, DB2), and middle-ware products (WebLogic, WebSphere). What benefits do error codes provide? What are the disadvantages to using error codes?
WITHIN a program one should always use exceptions instead of error codes. However, exceptions can't propagate beyond a program. Any time the error must leave the program you are left with error messages or error codes.
For simple things that will always be human-operated error messages without codes are fine. You can say "File not found" without giving it an error code. However, if it might be another computer on the other end then you should give error codes in addition. You don't want to break the other system when you change it to "File <x> not found".
I don't think I've ever used error codes in .Net except in one situation - when I was creating a console application that I knew was going to be called from another app. This other app had to know when the console app failed, and what went wrong. So, one example of when it would be appropriate would be when you know your program will be called by other programs, and you want a structured way for them to understand errors.
That said, I was a newbie to .NET at the time, and have never used error codes since.
As a side note, as a Windows guy, it's nice to be able to plop in an error code and come up with a KB article, so an error code combined with good documentation and the ability to find it = nice feelings from your users.
Very common for web service interfaces. It's very easy and standard to return a code with a description.
I agree that for most of the scenarios is old school
I'd say the biggest disadvantages it's the quality of code. You have to add more complex logic to manage error codes while exceptions are bubbled without having to use method parameters or return values.
You also have to add an "IF" to check if the returned code is SUCCESS or not, while exceptions goes directly to the error handling block.
I'm a newbie to stack overflow but...
I believe that error codes tend to be used or useful for dealing with erroneous situations that require an end-user of sorts to get involved to rectify a situation. If your code is to be maintained by another developer then exceptions is the way to go. However, in a situation where there is a problem:
in the environment that your application is running
with communication between your app and some other entity (web server, database, socket, etc)
that a device or device driver indicates (hardware failure maybe?)
then error codes may make sense. For example, if your app attempted to log into a database on behalf of your end-user, but the DB was unreachable for authentication (DB is off-line, cable is unplugged) then an error code/description combo might help the end-user rectify the problem.
Again at the developer/engineer level who will be able to touch the source code (traditional debugging and testing techniques) and modify it, use exceptions.
Hope this helps...
--jqpdev
I frequently use error codes when an error needs to be conveyed to the user, since they can be internationalized. For example, in a compiler, if there are errors in user code, errors can be signaled in the compiler backend, while the frontend can localize them into culture/language-specific strings for user consumption. Enums may be better for this purpose than raw integers, however.
I've also used them in creating an "error reporting" framework for the app. When exceptions were thrown, they were thrown with an error code, which, when the exception bubbled up, was sent (with a log) to the central server. The code helped organize the database so we could inspect logs related to a specific error.
Finally, as mentioned in a couple other answers, error codes are easy and language-agnostic to google (think Windows error codes/MS KB articles), so an error code with a description of what went wrong may be better for end-users of a technical product.
The idea of error codes is useful, but IMO they belong as exception members or as parameters to an IErrorReporter interface or something more ofthen than as method return values.
Error codes are old-school. They are of little to no value at all.
The only possible value to an error code is that it can identify a very specific circumstance. You could have a code for each point in the code base that can throw an exception. This would allow you to narrow down very precisely what the problem must be.
But nobody cares about that level of detail. Who wants to maintain such a mess. It would leave you with codes that meant something like "condition A and B but not C due to state S". It's more effort than it's worth to try to work out exactly what that means. A stack trace will be more valuable in telling you where in the program the problem occurred.
I learned to program computers before exceptions were a widespread technique. I'm so glad we got exceptions instead!
C#, and probably Java too, supports a better exception handling control flow, the finally keyword, which makes things a little nicer than using error codes. An exception object can contain any level of detail, certainly much more than an error code. So the exception object is way more practical, but you might run into an uncommon case where an error code would be more appropriate.
FWIW, C++ also supports exception objects. I don't think that C++ supports a finally keyword (though the newer C++ whatevers just might), but in C++ you also have to avoid things like returning inside a catch handler.
Error codes were designed in an age where the only way for a function to tell the caller that something went wrong was to assign a special meaning to one or more values of those which can be returned, and very frequently only a native integer or so was available for returning that special value.
For instance, in C the "get character" routine returns the next character value in ASCII, but returns a negative value if for some reason something went wrong. You are then responsible for returning to YOUR caller in a way so this error situation can be handled, and that must return etc.
The Exception mechanism is an elegant way to handle this "this is an emergency, we must return from code until something can deal with the problem". Error codes are inferior to this.
I've written many web services that are consumed by other (remote) applications. When things go badly with a request, customers more or less insist on getting a code, so that they don't have to do some horrific string comparison to find out what went wrong.
Take HTTP result codes as a fine example of this sort of behavior. "200" means happy, "300" could go either way, "400" or "500" means start freaking out.
Error codes are for if you want to send them to the user. If not, use an exception.
Sometimes you don't want to give too much information to the user when an error occurs. For example, a user is not able to sign a new contract. The error message only states something generic like "Cannot sign a new contract".
This adds difficulty to support cases where the user thinks this is not correct. If you have an error code, for example a number or an acronym, it could be part of the error message. The user wouldn't know what it means but the support staff could look it up and could then check if that specific reason for declining the new contract is indeed an error or not.

Do you have any good advice/links to a set of coding standards or best practices to follow?

For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
My best advice regarding coding standards: don't let them get in the way when trying to get work done.
A big bureaucracy might actually hinder progress in projects instead of helping to achieve better team work. When people complain about not following coding standards instead of the actual quality of the code, then it is too much regulation.
Other than that, pick one from the many suggestions and try to stick with it for as long as possible to build a code base following a single standard that you are used to.
Coding standards are good, but coding standards written from scratch in which the company reinvents the wheel, or coding standards imposed by a single "prophet", can be worse than having no coding standards at all.
This means:
Coding standards should be discussed and agreed upon.
The coding standards document should include the reasons behind each rule.
Coding standards should be at least partially based on reliable sources.
The sources I know of for the languages in your tags are:
For C++: The book C++ Coding Standards by Sutter/Alexandrescu.
For C#: 4 or 5 PDF's I found googling for C# Coding Standards :)
Adam Cogan has a great set of rules on his web site. There are coding guidelines, but there is much more there also.
Adam Cogan's Rules to Better...
Coding standards are great. We've been using Lance Hunt's C# Coding Standards for .NET almost without modifications
If you are maintaining code that continue to use the same standard as the original code was developed in (there is nothing worse then trying to debug a problem when the code looks all higgildy piggeldy)
Some comment to the post suggesting looking at the Google C++ guidelines. Detailed discussion about some aspects of these guidelines are posted at comp.lang.c++.moderated.
Some weird or controversial points include:
We don't believe that the available
alternatives to exceptions, such as
error codes and assertions, introduce
a significant burden.
As if assertions were a viable alternative... Assertions are usually for programming errors and situations that should never happen, while exceptions can happen (are somewhat anticipated) in the execution flow.
Reference Arguments: All parameters
passed by reference must be labeled
const. ... In fact it is a very strong
convention that input arguments are
values or const references while
output arguments are pointers.
No comment, about weasel phrase a very strong convention.
Doing Work in Constructors: Do only
trivial initialization in a
constructor. If at all possible, use
an Init() method for non-trivial
initialization.  ... If your object
requires non-trivial initialization,
consider having an explicit Init()
method and/or adding a member flag
that indicates whether the object was
successfully initialized.
Yes... 2-phase init to make things simpler... What if I have const fields? This rule is probably the effect of attitude towards exceptions.
Use streams only for logging
Which streams? IOStreams, standard C streams, other?
On one hand they advise to use macros only in exceptional situations, while they recommend using DISALLOW_COPY_AND_ASSIGN to prohibit copy/assign. They could have advised the approach with special class (like in Boost)
Do not overload operators except in rare, special circumstances.
What about assignment, or arithmetic operators for numeric calculations, etc?
Default parameters are more difficult to maintain because copy-and-
paste from previous code may not reveal all the parameters. Copy-and-
pasting of code segments can cause major problems when the default
arguments are not appropriate for the new code.
The what? Copy/paste from previous code?
Remember that reading any of the guidelines can introduce a bias to your way of thinking. And sometimes it won't be beneficial for you or your code. I agree with some other posts advising reading good books by good authors beforehand. When you have sufficient amount of knowledge, then you are able to look at the guidelines and find good and weak points easily, without creating a mess in your brain ;)
If you plan to introduce a code-formatting standard to an existing programming team, get input from each member of the team so they'll have "buy in" and be more likely to write code to that standard.
Programming styles are as difficult to change as habits, and you'll have to accept that some people won't make their code 100% compliant 100% of the time. It would be worth your time to find (or write your own) pretty-printer program and periodically run all your code through it to enforce consistency. (I always felt uneasy when manually checking in source code changes that only consisted of formatting corrections for other peoples' code; I worried that others would label me a nitpicker.)
Sun Java Code Conventions
Python Style Guide
Zend Coding Standard for PHP
Having asked this question. I found that the accepted answer proved to be sufficient for my needs.
However, I realise that this is not a 'one-size-fits-all' scenario, so there is a large quantity of information within the thread that you may find more or less useful. Weel worth a read!
For Java and other C-family languages I recommend Sofware Monkey's coding standards (of course, since they're mine).
In general, keep them simple, and provide examples and justification for every requirement.
What's in the standard doesn't really matter all that much. What matters is that you have one, and that your developers follow it.
It doesn't quite answer the question, but it's worth a mention...
I read Steve McConnell's Code Complete. Whilst it doesn't give you a pre-baked set of coding standards it does set out a lot of good arguments for the various approaches. It'll make you think about things you'd not thought of before.
It changed my little world for the better.
Coding standards themselves are great and all, but what I think is much, much, MUCH more important is keeping with the style of whatever code you're maintaining. I've seen people add a function to some class written one way and forcing their coding standard on just that function. It's inconsistent, it sticks out, and, in my opinion, it makes it harder to enjoy the class "as a whole".
Whenever you're maintaining code, look at the code around it. See what the style is. K&R braces? Capital Camel Case methods? Hungarian? Double-line comment blocks between every function? Whatever it is, you should do it too in that specific area.
Before I leave, one thing I'd like to note that's related - naming files. I'm mainly a C++ guy, so this may not apply to whatever else, but basically it goes _.h or .cpp. So, Foo::Bar would be in Foo_Bar.h. Common things (i.e. a precompiled header) for the Foo namespace would be in Foo_common.h (note the lowercase common). Of course, that's a taste thing, but everybody who has worked with this has come out in favor of this.
i think Code Craft - The Practice of Writing Excellent Code pretty much sums it all up
Very popular are Ellemtel rules for C++.
For C# I recommend Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition) (Microsoft .NET Development Series).
Mono Coding Guidelines
The answers here a pretty complete, thus I am not pointing to another coding standard document. However, once you decided to stick to one style you should use an automated coding style enforcer throughout your team.
For Java there is checkstyle and for .NET Microsoft Style Cop.
Here is a similar discussion on Stackoverflow: C# Coding standard / Best practices
Camel and pascal casing alone solves a lot of coding standard problems

Finding out what exceptions a method might throw in C#

Is there any way to find out what exceptions might be thrown by any method in .NET code? Ideally I want to see what might be thrown and choose which ones I want to handle. I guess I want the information you'd get from the throws clause in java.
The situation is I'm doing a linq query on an xml document from the network and want to know what could go wrong. I could open up the assembly in reflector and have a look but I thought there might be an easier way.
.NET does not have enforced ("checked") exceptions like java. The intellisense might show this information, if the developer has added a /// <exception.../> block - but ultimately more exceptions can happen than you expect (OutOfMemoryException, ThreadAbortException, TypeLoadException, etc can all happen fairly unpredictably).
In general, you should have an idea of what things are likely to go wrong, and which ones you can actually do something useful about. In most cases, the correct behaviour is to let the exception bubble up (just running any "finally" code to release resources).
Eric Lippert has a good blog on this subject here.
I think that Exception hunter can provide this information however it costs money...
After reading another article about this on StackOverflow, I built on top of that other answer to write a tool to do this, you can get the source code from GitHub here:
Exception Reflector
you can also read more here:
http://steves-rv-travels.com/archives/167
As long as you're using BCL classes, they are all completely documented and Intellisense therefore displays any exception a method can throw. Other than that (and reading the docs), there is no way, I think.

Categories

Resources