Checking exceptions in .NET solution (sources or binaries) - c#

I am search a way to disable usage (**throw new exception **) of specific exception in our c# solution.
If can I configure c# compiler and show compiled error if somebody try to throw a specific exception or, maybe, can I call a utility and analyze compiled binaries and show message if the specific exception was raises in our solution?
I am not look run-time solutions. I want to check in "development" time.
Igor.

You may consider adding a custom rule(Warning/Error) to the FxCop and then build the solution after adding the FxCop project file into your solution.

If the exception in question is your own exception, you can decorate the exception class with the Obsolete attribute. Then the compiler will show a warning whenever the class is used.
[Obsolete("MyException is obsolete. Please use MyOtherException instead")]
public class MyException : Exception
{
}

Give Gendarme a look; I'm not sure how trivial it is to write a new rule that can do what you want, but I'm hoping it would be easy enough. Failing that, check out StyleCop.

Related

Attribute to inform method caller of the type of exceptions thrown by that method

I'm not looking to implement the Java "throws" keyword. See http://www.artima.com/intv/handcuffsP.html for a discussion on the merits of the throws keyword and why it was not implemented in C#.
I am, however, curious if there's a way to create an attribute like the following:
[ThrowsException( exceptionType = NullReferenceException )]
[ThrowsException( exceptionType = AuthenticationException )]
public void Login( Credentials credz )
{
// ... etc...
}
such that - when calling a method which has been decorated with one or multiple ThrowsException attributes, the type of exceptions thrown by said method (at least the ones that are explicitly declared by the ThrowsException attribute) would be visible in the method's documentation
This is not the same as the Java "throws" keyword as it would not require that the caller handle these exceptions. Doing so could introduce breaking changes e.g. in a client application that does not handle new exceptions introduced by a version change.
While one could use:
/// <exception cref="member">description</exception>
My intent for using attributes is so that the project does not compile if the name of the exception has been changed or if the exception no longer exists. Therefore, How To Document Thrown Exceptions, is not the same question.
Update: 2013-05-23
I've figured out a way to resolve via the use of an attribute and without the use of plug-ins. I will try to get around to it this weekend and will be happy to post the solution if it works as expected. If someone beats me to posting a solution, I will happily accept their answer.
Since I won't be able to get around to this until Monday, I'm offering a bounty if you can beat me to it - An acceptable answer would:
( not include the use of a visual studio plug-in or any third-party tool
&& provide a way to include the exception(s) in the XML documentation
&& ensure type safety is enforced during compilation )
|| prove it is not possible to meet the preceding three requirements in order to provide a solution to the problem posed in this question
I would consider it acceptable for the XML documentation not to reflect the exceptions, from the ThrowsException attributes, until after the project has been built.
It would be interesting to see a Resharper-based solution (since it is common to most of the development shops I have worked in), but it will not be accepted if there is a solution that remains agnostic of third-party tools. Similarly, a solution that works only in Visual Studio would be accepted over a solution dependent on Resharper, but it would not be accepted if there is a solution that would work in other IDEs e.g. MonoDevelop (more frameworks supported - even better).
In C# you document classes and their members with a XML documentation. In Visual Studio, start typing slashes over something and by the third slash it'll auto-generate the most common tags for you to fill in. It looks vaguely like Javadoc and JSDoc.
You are looking, specifically, for this tag.
My intent for using attributes is so that the project does not compile
if the name of the exception has been changed or if the exception no
longer exists. Therefore, How To Document Thrown Exceptions, is NOT
the same question.
You can do this without using attributes, instead by writing <exception> documentation and configuring your project like this:
Project properties -> 'Build' tab:
'Output' section: Check 'XML documentation file'.
'Treat warnings as erros' section: Check 'Specific warnings' and add warning 1574.
This way project won't compile if XML documentation cref attribute value cannot be resolved.
The below should work
[ThrowsException( ExceptionType = typeof(NullReferenceException) )]
Your attribute will have a property of type Type
Type ExceptionType { get; set; }

Source of System.NullReferenceException

I am implementing a error logger for a web shop and just logging a NullReferenceException in a specific class is only useful to a certain level. I am not really interested in how to prevent the exception, as I am aware of that, but sometimes it still happens thus the error logger.
Then the question is: How do I find the source of a System.NullReferenceException inside all the exception information.
Make sure you log the full stack trace. Assuming you've got debug information turned on (no reason not to for a web app...) you should be able to get to the line which caused the problem.
Of course, that won't always give you all the information you need, if you've got:
if (foo.Bar.Baz && person.Address.Road.Length)
in a single line... but it's the best starting point you'll get.
Additionally, adding argument validation to methods can make it a lot simpler to pin down what's wrong. Personally I'm a fan of helper methods for this. For example, in Noda Time we have Preconditions, so I can just call:
Preconditions.CheckNotNull(foo, "foo");
(which also returns the value of foo, which is handy in constructors which are copying arguments into fields).
The earlier you can detect the unexpectedly-null reference, the better.
If I understand the question correctly, in Visual Studio, go to Debug > Exceptions, and check all options to throw exceptions. This will allow you to see everything that is being thrown while debugging. You can possibly use the contents of InnerException to determine what the root location of the error is being caused.

Create C# code analysis rule that generates compiler error

From time to time, I encounter annoying bugs in the .NET framework that the compiler cannot clearly point out at both compile time and runtime. This for example.
It states that if you wire up the MvcApplication.BeginRequest manually in Application_Start from Global.asax.cs, you'll get a NullReferenceException in System.Web.HttpRuntime.ProcessRequestNotificationPrivate.
Since there is no clear way to relate the error to the cause, it would be nice to be able to write something that states that if you wire up event MvcApplication.BeginRequest from MvcApplication.Application_Start, to throw an compile time error, forcing you to remove it and explain why.
You can implement a custom FxCop rule which checks if the handler is wired up as you said and include that rule in your code analysis ruleset. Check out the rule CA2001, it does something similar to what you want to achieve.
For information on implementing custom FxCop rules see http://www.binarycoder.net/fxcop/index.html.

Where to find information on exceptions thrown by classes and methods?

I am trying to add more specific error handling to my c# app, but I am finding it hard to track down what exceptions are thrown by classes and method. Is there a way through visual studio 2010 to find this info, or maybe an exception list?
Just find the class/method you are interested in on MSDN.
For example, look at this page for the Dictionary.Remove Method. If the method throws an Exception (like this one), you can get the information for the Exceptions section of the page.
If you are talking about .Net framework methods, they are documented in the hover over help. You will see Exceptions: . Or you can see it in the object browser Ctrl+W, J as well. Or press F1 over a function to go to MSDN help, where they are documented in detail.
If you're allowing the exceptions to be thrown, you should be able to see the exception details in the Event Viewer in Administrative Tools.
You can find specific uses of a particular exception, but there is no complete listing of all exceptions any method might throw.
Consider the following method:
public void SomeMethod()
{
SomeObject x = null;
x.SomeMethod(); // NullReferenceException
File.Open("SomePath", FileMode.CreateNew); // Any number of File Exceptions potentially
throw new CustomException();
};
How would a code analyzer be able to determine which potential exceptions there were?
If you're looking for information on a specific class, I'd check the documentation for it.

Why doesn't Visual Studio show an exception message when my exception occurs in a static constructor?

I'm running this C# code in Visual Studio in debug mode:
public class MyHandlerFactory : IHttpHandlerFactory
{
private static Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
static MyHandlerFactory()
{
myDictionary.Add("someKey",true);
myDictionary.Add("someKey",true); // fails due to duplicate key
}
}
Outside of the static constructor, when I get to the line with the error Visual Studio highlights it and pops up a message about the exception. But in the static constructor I get no such message. I am stepping through line-by-line, so I know that I'm getting to that line and no further.
Why is this?
(I have no idea if that fact that my class implements IHttpHandlerFactory matters, but I included it just in case.)
This is VS2005, .Net 2.0
Edit: I just want to add, the fact that it's an HttpHandler does seem to matter. As the answers have indicated, the default behavior is to break on the TypeInitializationException rather than the inner exception. I tested another example without the HttpHandler and saw that this caused the program to break on the first line that used the class. But in this case there's no line in my code to break on, since the class was only called as an HttpHandler specified in my web.config file. Hence, it didn't break on the exception at all.
The problem is that the exception thrown is actually a TypeInitializationException that wraps whatever exception is thrown. I'm not sure what design tradeoffs caused this, but IMO it's one of the most annoying things in .NET development, and I'm sad to see it's still around in .NET 4.
In VS, to catch the exception ASAP, you'll need to turn on first-chance exceptions. Go to Debug > Exceptions and check "Common Language Runtime Exceptions", which will break as soon as an exception is thrown.
(Note: if you're using the Dynamic Language Runtime, you'll need to be more choosy about what exceptions are caught, since that apparently uses exceptions for flow control).
I tried your code and I got the TypeInitializationException as you expected. No problem in my VS...
But if you run this (or any other) application 'without debugging', you should always get an error message for any unhandled exceptions - no VS settings will make a difference here.
The static constructor gets run before your application is running in an appdomain. This is probably causing issues with the way VS is catching the exception, which from your description is quite non standard. It may be a limitation of 2005. That's why you should always catch within the body of the static constructor. There is an excellent discussion of this in the new book Effective C#

Categories