To throw exceptions, I usually use built-in exception classes, e.g. ArgumentNullException and NotSupportedException. However, sometimes I need to use a custom exception and in that case I write:
class SlippedOnABananaException : Exception { }
class ChokedOnAnAppleException : Exception { }
and so on. Then I throw and catch these in my code. But today I came across the ApplicationException class - should I be using that instead? What's it for?
It does seem inefficient to have lots of effectively identical Exception classes with different names (I don't usually need any individual functionality). But I dislike the idea of catching a generic ApplicationException and having to use extra code to determine what the error was.
Where should ApplicationException fit in with my code?
The short answer is: nowhere.
It is a relic of the past, where Microsoft intended developers to inherit all their custom exceptions from ApplicationException. Shortly after, they changed their mind and advised that custom exceptions should derive from the base Exception class. See Best Practices for Handling Exceptions on MSDN.
One of the more widely circulated reasons for this comes from an exerpt from Jeffery Richter in Framework Design Guidelines:
System.ApplicationException is a class that should not be part of the .NET Framework. The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException. However, a lot of exception classes didn't follow this pattern. For example, TargetInvocationException (which is thrown by the CLR) is derived from ApplicationException. So, the ApplicationException class lost all meaning. The reason to derive from this base class is to allow some code higher up the call stack to catch the base class. It was no longer possible to catch all application exceptions.
So there you have it. The executive summary is that ApplicationException is not harmful, just useless.
According to the remarks in msdn:
User applications, not the common language runtime, throw custom exceptions derived from the ApplicationException class. The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system.
If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.
Derive them from Exception. Also, I don't see a problem with creating new exceptions for your cases, as long as it is warranted. If you encounter a case where there is already an exception in the framework, use that, otherwise, roll your own.
In the initial design, in .NET 1.0, it was planned that the framework itself will throw SystemException and derived; while user applications - will throw ApplicationException and derived.
But later, in .NET 2.0, that was dropped.
Thus derive from Exception.
Related
I am writing windows runtime behavior for FlipView memory efficient image loading where I expose my IImageSourceProvider interface. Library users could write their own interface implementation (which implies that it could throw different types of exceptions) so I'm curious is it possible to intercept exceptions by type given in runtime (perhaps by some reflection) ? The main idea is to give library-users ability to register exceptions types and their handlers (because it's "xaml component" they won't be able to handle it in code at least without any "hacks").
In C# one could specify which exceptions should be thrown in an implementation of the interface using comments
http://msdn.microsoft.com/en-us/library/w1htk11d.aspx
This will leave it up to the implementer to wrap his exception a custom exception that your interface is allowed to throw.
Barring that you could catch a generic exception and then use reflection to inspect the type and properties of the caught exception class.
I'm creating a custom C# collection by implementing ICollection in my class and have noticed some of the methods defined by the interface have exceptions documented i.e. http://msdn.microsoft.com/en-us/library/0efx51xw(v=vs.110).aspx
None of the examples or documentation I've seen for implementing interfaces seem to talk about needing to implement raising exceptions. Whenever the documentation for a method in an interface shows exceptions could be raised by the method should I be checking for each of these conditions and raising the exceptions within my implementation code?
When documenting an interface, it is common to include xml documentation to indicate the exceptions that may be thrown by implementations. This doesn't mean that implementations MUST be able to throw these, just that they MAY throw them.
See Liskov's Substitution Principle. Specifically "No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype." -http://en.wikipedia.org/wiki/Liskov_substitution_principle
I am continuing with my exam revision.
I have come across the usage of the Base Exception class and I have seen it on exam papers also.
My question is when do you derive from the Base Exception class?
I am of the impression if you want a custom class to throw an exception with more meaningful information, then you can create a custom exception class that contains the exact data that is representative of how your custom class is used and what scenario it is designed to be used for?
Why can't my custom exception class derive from 'ApplicationException' or 'SecurityException' or the base 'Exception' class?
I am of the impression that I should derive from the base Exception class and not the previous two.
My question second is, when would you derive from the other two??? Are there any clear-cut
distinctions as to when you would derive from either one of these three? Assuming there are no others I have I have missed out?
SMALL UPDATE:
This question from transcender pretty much hits the nail on the head.
*Which class should you use to generate an application-specific exception?
Answer: The ApplicationException class*
This is all discussed in the Design Guidelines document.
In our most recent project we used a base exception class. We used it to get the following functionality:
All exceptions needed a number, so defining the property for the number was done in the base class
All exception messages needed to be formatted the same way, with the number, reason and type. This get formmated message was done in the base class.
Our base exception class derives from ApplicationException. This may have been a mistake, there is a lot of discussion about problems with too much depth of inheritance. However, we have not had any problems with this.
One tip for the exam: Read the question very carefully. Good luck.
In general, you want to derive from the Exception class which most closely resembles the type of exception you want to throw. If the trouble is that some Argument or Parameter has been passed which causes a problem, use ArgumentException. If you need some customization with that, inherit from ArgumentException.
In my experience, the only two reasons to use the base Exception are: 1) when you need some custom exception that completely does not fit one of the current exception models or 2) When a method could theoretically throw a number of exceptions, but you've already caught the ones you find most likely to be thrown.
Typically, I don't inherit from exceptions at all. Simply setting the Message property tends to be enough.
Ideally, exceptions should be grouped in a hierarchy such that if code will want to handle several exceptions the same way, they will all be derived from a common base class. If the base throw-able type had been an interface rather than a class, such an ideal might have been somewhat achievable. As it is, however, the single-inheritance limitation for classes severely limits the usefulness of the hierarchy.
The only time an exception hierarchy is apt to be a useful concept is when an implementation of an interface, or a new version of a class, which is documented as throwing certain exceptions wants to allow code to distinguish among more distinct conditions than are reported by those exceptions. In such a scenario, having a method throw exceptions which do not derive from the documented ones would be a breaking change, so one must throw an exception that inherits from the documented one which best describes the previously-unanticipated condition. That's rather ugly, but the exception-handling mechanism doesn't really provide any better alternative. It's rather unfortunate that things like IEnumerator<T>.MoveNext() aren't documented as throwing any exception which would simply mean "Sorry--the system isn't on fire or anything, and I don't know that anybody's changed the collection, but I can neither advance to the next item nor truthfully say the enumeration is complete", but they don't.
Other than the case where one needs to throw an exception that's compatible with existing code, it may be helpful to have the exceptions used by an application or library derive from a common base. Instead of using ApplicationException it should be something like YourApplicationNameException or YourLibraryNameException--something that nothing else is apt to derive from. Something like ApplicationException is bad because code which does a catch ApplicationException will get not only the exceptions which it derived from that type, but also any exceptions which any other libraries derived from it.
If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?
See Creating and Throwing Exceptions.
On throwing built-in exceptions, it says:
Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.
and
Do Not Throw General Exceptions
If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.
Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception."
This blog entry also has some useful guidelines.
Also, FxCop code analysis defines a list of "do not raise exceptions" as described here. It recommends:
The following exception types are too general to provide sufficient information to the user:
System.Exception
System.ApplicationException
System.SystemException
The following exception types are reserved and should be thrown only by the common language runtime:
System.ExecutionEngineException
System.IndexOutOfRangeException
System.NullReferenceException
System.OutOfMemoryException
So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation).
Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).
On the subject of System.Exception and System.ApplicationException: The latter was meant to be used as the base class of all custom exceptions. However, this hasn't been enforced consistently from the beginning. Consequently, there's a controversy whether this class should be used at all rather than using System.Exception as the base class for all exceptions.
Whichever way you decide, never throw an instance of these two classes directly. It's actually a pity that they aren't abstact. For what it's worth, always try using the most specific exception possible. If there is none to meet your requirement, feel free to create your own. In this case, however, make sure that your exception has a benefit over existing exceptions. In particular, it should convey its meaning perfectly and provide all the information necessary to handle the situation in a meaningful manner.
Avoid to create stub exceptions that don't do anything meaningful. In the same vein, avoid creating huge exception class hierarchies, they're rarely useful (although I can imagine a situation or two where I would use them … a parser being one of them).
I use the ArgumentException (and its “friends”) regularly.
NotSupportedException and NotImplementedException are also common.
My advice would be to focus on two things:
Scenarios
User expectations
In otherwords, I would sit down and identify:
Under what scenarios do you want to throw exceptions.
In those scenarios, what would the users of your API expect
The answer to #1 is, of course, application specific. The answer to #2 is "what ever similar code they are already familiar with does".
The behavior that comes out of this is:
Under the scenarios that arise in your programs that also arrive inside the
framework, such as arguments being null, out of range, being invalid, methods not
being implemented, or just not supported, then you should use the same exceptions the
framework uses. The people using your APIs are going to expect that they behave that
way (because that's how everything else behaves), and so will be better able to use
your api from the "get go".
For new scenarios that don't exist in the framework, you should go ahead and invent
your own exception classes. I would say that you should prefer Exception as your base
class unless their is some other base exception that provides services you need.
Generally speaking I don't think something like "ApplicationException" will help you
much. When you start defining your own exceptions there are a few things you should
keep in mind though:
a. The primary purpose of an exception is for human communication. They convey
information about something that happened that shouldn't have. They should provide
enough information to identify the cause of a problem and to figure out how to
resolve it.
b. Internal consistency is extremely important. Making your app behave as universally
as possible under similar circumstances will make you API's users more productive.
As far as there being hard and fast rules about what you should and should not do... I wouldn't worry about that stuff. Instead I would just focus on identifying scenarios, finding the existing exception that fits those scenarios, and then carefully desining your own if an existing one doesn't exist.
You can create and throw pretty much any of them, but you generally shouldn't. As an example, the various argument validation exceptions (ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, etc) are suitable for use in application code, but AccessViolationException isn't. ApplicationException is provided as a suitable base class for any custom exception classes you may require.
See this MSDN article for a list of best practices - it refers to handling exceptions, but also contains good advice on creating them...
I have an application which tries to load some expected registry settings within its constructor.
What is the most appropriate .NET Exception from the BCL to throw if these (essential, non-defaultable) registry settings cannot be loaded?
For example:
RegistryKey registryKey = Registry.LocalMachine.OpenSubkey("HKLM\Foo\Bar\Baz");
// registryKey might be null!
if (registryKey == null)
{
// What exception to throw?
throw new ???Exception("Could not load settings from HKLM\foo\bar\baz.");
}
Why not create your custom exception?
public class KeyNotFoundException : RegistryException
{
public KeyNotFoundException(string message)
: base(message) { }
}
public class RegistryException : Exception
{
public RegistryException(string message)
: base(message) { }
}
....
if (registryKey == null)
{
throw new KeyNotFoundException("Could not load settings from HKLM\foo\bar\baz.");
}
Also, instead of inheriting from Exception you could inherit from ApplicationException. This depends on the kind of failure you want your application to have in this situation.
actually, I wouldn't throw an exception here. I would have a default value, and then create the key using that default value.
If you MUST have a user-defined value, I'd use the ArgumentException (as that's fundamentally what you're missing, an argument for your constructor--where you store it is irrelevant to the type of exception you're trying to generate).
I'd go with ArgumentException or ArgumentOutOfRangeException..
throw new ArgumentException("Could not find registry key: " + theKey);
Quoting MSDN:
The exception that is thrown when one
of the arguments provided to a method
is not valid.
...
IMO writing a proper exception message is more important.
It depends on why it failed. If it's a permissions issue, the I'd go with System.UnauthorizedAccess exception:
The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
I don't know if it matches the "specific type", but it is a security error, and access wasn't authorized.
On the other hand, if the item just doesn't exist then I'd thrown a FileNotFound exception. Of course, a registry key isn't a file, but FileNotFound is pretty well understood.
Since this entry is as you put it an essential value, what is the impacts to your application if this value cannot be obtained? Do you need to hault operations or do you simply need to notify the application.
Also, there are a number of reasons that the value could be null
User doesn't have permission to read the key
The key doesn't exist
Does this impact the action you take when working with the application?
I think that these types of scenarios play into what exception to throw. Personally I would never throw just Exception, as it really is a "no-no" from a standard design practice.
If it is due to a user not having permissions, AND then not having this permission might cause future problems I would vote for an UnauthroizedAccess exception.
If the issue is not a critical issue, but you really need to know that the key isn't there I would strongly recommend the "KeyNotFoundException" implementation mentioned elsehwere.
When throwing an exception you want to make sure that the exception being thrown is descriptive and provides all needed information, thus why I think it depends on the root cause as well as the overall impacts to the application.
To quote MSDN's "Design Guidelines for Developing Class Libraries"
ApplicationException
If you are designing an application
that needs to create its own
exceptions, you are advised to derive
custom exceptions from the Exception
class. It was originally thought that
custom exceptions should derive from
the ApplicationException class;
however in practice this has not been
found to add significant value. For
more information, see Best Practices
for Handling Exceptions.
I think that the best approach is to take a step back. If there is not a clear cut exception that describes what is happening, it takes only minutes to define one. Try to avoid repurposing exceptions because it "is close enough".
My recommendation is that you should create a base exception class which inherits from either Exception or ApplicationException. This will allow for you to easily identify, from your stack trace, whether the exception is a custom exception that you defined or whether it originated somewhere else. All of your custom exceptions should inherit from the base exception that you create.
Note: I am not going to recommend the use of either Exception or ApplicationException. There is enough debate in the community vs. Microsoft's documentation over which should be used and for what purpose. On a personal level, I choose Exception as my base exception.
If there is not a clearly predefined exception that matches your intent, going forward, derive a custom exception from your base exception. It definitely helps in tracing down the origin of a problem, makes them easier to handle (imagine that an existing framework exception was thrown in the block of code, but by the framework or another method), and just plain makes sense.
Keep in mind, you can have multiple exception hierarchies to group like exceptions together. For example, I can have MyBaseException which inherits either ApplicationException or Exception. I then can have a more generalized MyRegsitryException which inherits from MyBaseException. Then I can have specific exceptions, such as MyRegistryKeyNotFoundException or MyRegistryKeyPermissionException.
This allows you to catch a grouped exception on a higher level and reduce the number of catches that you might have that contain redundant handling mechanism. Combine this with isolating the scope of the exceptions to specific namespaces that would use them, and you have the start of a very clean exception handling scheme.
I would probably throw an ApplicationException since this is specifically related to your application. Alternatively, you could throw a ConfigurationErrorsException, though this is usually associated with an error parsing an application configuration file, not reading the configuration from the registry.
The other potential exceptions that come to mind are ArgumentException or ArgumentNullException, but these have a connotation of being related to parameters that are passed into the method and are not, therefore, appropriate to my mind. It could easily lead someone using/modifying your code astray when trying to determine why it is not working.
In any case, a good, descriptive error message is probably the most effective way of communicating what the problem is.
EDIT: Note that throwing an exception on a null value doesn't mask any exceptions that would occur when attempting to read the registry value. I believe that any SecurityException that gets thrown when you attempt to read the value without sufficient privileges will still occur as long as you don't wrap it in a try/catch block.
I think just Exception itself could do the job. If your message is descriptive enough, then it's all good. If you really want to be precise about it, then I'd agree with petr k. Just roll your own.