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.
Related
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.
I'm working on a logging program, and I'd like to avoid processing the same Exception object repeatedly when it is being logged repeatedly because it is percolating up through a nested call structure. So I'd like to be able to format the Exception object once, and give the formatted version a unique "exception number" and then tag the Exception object somehow so I can recognize it if it turns up again in a later log call.
The idea I've come up with is to misuse the HelpLink field of the Exception object. I'll set it to contain a string version of my "exception number". Then I can recognize the Exception object if it shows up again momentarily in another log call.
But is this maybe a bad idea? Are there any gotchas involved that I haven't thought of? If so, does anyone have a better idea?
EDIT:
To explain the situation a bit more, this logger will only be used on my own programs.
Instead of 'abusing' HelpLink property, you could use Data property to add extra information to the Exception. It contains key/value pairs that provide additional user-defined information about the exception.
While I agree with TheVillageIdiot, I would point out that more generally speaking, if you want to change the behavior of Exception, then you should create your own Exception class that add's additional pertinent information. That's why we use inheritance and polymorphism, after all. :)
Definitely it is not okay to use Exception.HelpLink because logger should be concerned with logging the exception information only in given format or any default format. If same exception is coming again and again it is problem of the executing assembly or program not the logger.
Better still you can explore the options of using log4net for logging and custom reporting interface to format/group exception from the log files or database tables created/updated by log4.net
No it is not acceptable to misuse the HelpLink. As #Greebo mentioned if you need additional properties you could create your own exception classes. An alternative might be to use the Data property that is part of the System.Exception class.
Question: Are your exception handlers doing any handling other than logging?
If not then most likely your don't need the handlers. Just let the exception (using a finally block for cleanup) bubble up the call stack and handle it at the outmost layer. If your handlers are handling the exception then I'm not sure why you would have the same exception further up the stack. I would think it would be more likely that you would create a new exception setting the inner exception to the one that was handled.
Your code should not be catching and logging the exception at every level. There's no reason that your code should ever be seeing the same exception twice. This sounds very much like you are using "catch every exception", which is a major anti-pattern.
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.
I am using the ReportServices Web Services API and I want to determine the exceptions that can be thrown by it.
Is there an easy way to do that?
C# does not have exception specifiers like Java does, so the primary way to determine what exceptions a method throws is to look at the documentation and hope that the developers documented the possible exceptions.
Assuming you're talking about the SQL Server Reporting Services Web Service, it looks like their online API reference does mention exceptions. For example, for CreateSchedule it says:
This method throws an
rsUnsupportedParameterForModeException
exception if a non-null value is
specified for the SiteUrl parameter in
Native mode.
Alternatively, if you have lots of time, you can use Reflector to dig through the implementation of the API methods you call (and the methods they call, and so on...) to see what gets thrown.
Keep in mind that exceptions can still be raised due to internal errors. You can look up the documentation and have a look at the exceptions manually raised, but some NullReference or OutOfMemory can still occur.
Getting an complete list will be quite painful.
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#