What exception classes already exist and when do we use them? - c#

In .net, c#
There are many sub-classes of Exception already existing,
what are they and when do we use them instead of creating our own sub-class?
This question is duplicate of c# is there an exception overview

The link provided by Jason is pretty comprehensive, but a lot of the exception types in it (such as NullReferenceException or IndexOutOfRangeException) are really only ever thrown by the framework; it would not be very appropriate for you was a developer to explicitly throw them.
Here are, in my opinion, a handful of the most useful exception types for a developer.
ArgumentNullException
This one's obvious: one of the arguments passed to a method was null, but for this particular method, a null value for that argument is not allowed.
ArgumentOutOfRangeException
A value was supplied to a method that is outside of the range that makes sense for that method.
Example
In most methods that take a parameter representing a magnitude or length, only positive values make sense for that parameter. So a check such as
if (x < 1)
{
throw new ArgumentOutOfRangeException("x");
}
is common.
FormatException
This is a pretty reasonable choice when you're writing your own custom text-parsing method, or really any code that expects strings to match a certain format, and some input is supplied that the code can't understand.
InvalidOperationException
I tend to use this one a lot (probably overuse it, actually) whenever I'm not sure what else to use. Generally I think of this type as conveying that the client attempted to do something illegal, for reasons relevant to the current class or method.
Example
Many IEnumerator<T> implementations throw an InvalidOperationException when the collection they're enumerating is modified. This is a reasonable design choice, as it is much easier to design a collection class that does not handle this case than it is to design one that does.
NotSupportedException
This one typically makes sense in a class that derives from some base class and only offers a partial implementation of that base class's abstract members.
Example
Some developers choose to write base classes with "optional" functionality that may be provided by derived classes or may not be. Below is an example:
abstract class Animal : Organism
{
public virtual bool EatsPlants
{
get { return false; }
}
public virtual void EatPlant(Plant food)
{
throw new NotSupportedException();
}
public virtual bool EatsAnimals
{
get { return false; }
}
public virtual void EatAnimal(Animal food)
{
throw new NotSupportedException();
}
}
class Herbivore : Animal
{
public override bool EatsPlants
{
get { return true; }
}
public override void EatPlant(Plant food)
{
// whatever
}
}
Obviously this is just my own personal (and subjective) list; but I thought it might give you an idea of what kinds of exceptions you can and should be leveraging within your own code.

Here is list of common exception types. If you want to know when to create your own exceptions, then try:
What are some best practices for creating my own custom exception?

For a list of sub-classes of Exception I recommend that you use the .NET Reflector.
http://www.red-gate.com/products/reflector/

Related

Why do I need an explicit interface declaration here? (C#) [duplicate]

The use case is some what like this:
public class SomeClass : ICloneable
{
// Some Code
// Implementing interface method
public object Clone()
{
// Some Clonning Code
}
}
Now my question is Why is it not possible to use "SomeClass(As it is derived from object)" as a return type of Clone() method if we consider the Funda's of Covariance and Contravariance?
Can somebody explain me the reason behind this implementation of Microsoft ????
Let me rephrase the question:
Languages such as C++ allow an overriding method to have a more specific return type than the overridden method. For example, if we have types
abstract class Enclosure {}
class Aquarium : Enclosure {}
abstract class Animal
{
public virtual Enclosure GetEnclosure();
}
then this is not legal in C# but the equivalent code would be legal in C++:
class Fish : Animal
{
public override Aquarium GetEnclosure() { ...
What is this feature of C++ called?
The feature is called "return type covariance". (As another answer points out, it would also be possible to support "formal parameter type contravariance", though C++ does not.)
Why is it not supported in C#?
As I've pointed out many times, we don't have to provide a reason why a feature is not supported; the default state of all features is "not supported". It's only when huge amounts of time and effort are put into making an implementation that a feature becomes supported. Rather, features that are implemented must have reasons for them, and darn good reasons at that considering how much it costs to make them.
That said, there are two big "points against" this feature that are the primary things preventing it from getting done.
The CLR does not support it. In order to make this work we'd basically have to implement the exactly matching method and then make a helper method that calls it. It's doable but it gets to be messy.
Anders thinks it is not a very good language feature. Anders is the Chief Architect and if he thinks it is a bad feature, odds are good its not going to get done. (Now, mind you, we thought that named and optional parameters was not worth the cost either, but that did eventually get done. Sometimes it becomes clear that you do have to grit your teeth and implement a feature that you don't really like the aesthetics of in order to satisfy a real-world demand.)
In short, there are certainly times when it would be useful, and this is a frequently requested feature. However, it's unlikely that we're going to do it. The benefit of the feature does not pay for its costs; it considerably complicates the semantic analysis of methods, and we have no really easy way to implement it.
A non-broken implementation of interface-implementation variance would have to be covariant in the return type and contravariant in the argument types.
For example:
public interface IFoo
{
object Flurp(Array array);
}
public class GoodFoo : IFoo
{
public int Flurp(Array array) { ... }
}
public class NiceFoo : IFoo
{
public object Flurp(IEnumerable enumerable) { ... }
}
Both are legal under the "new" rules, right? But what about this:
public class QuestionableFoo : IFoo
{
public double Flurp(Array array) { ... }
public object Flurp(IEnumerable enumerable) { ... }
}
Kind of hard to tell which implicit implementation is better here. The first one is an exact match for the argument type, but not the return type. The second is an exact match for the return type, but not the argument type. I'm leaning toward the first, because whoever uses the IFoo interface can only ever give it an Array, but it's still not entirely clear.
And this isn't the worst, by far. What if we do this instead:
public class EvilFoo : IFoo
{
public object Flurp(ICollection collection) { ... }
public object Flurp(ICloneable cloneable) { ... }
}
Which one wins the prize? It's a perfectly valid overload, but ICollection and ICloneable have nothing to do with each other and Array implements both of them. I can't see an obvious solution here.
It only gets worse if we start adding overloads to the interface itself:
public interface ISuck
{
Stream Munge(ArrayList list);
Stream Munge(Hashtable ht);
string Munge(NameValueCollection nvc);
object Munge(IEnumerable enumerable);
}
public class HateHateHate : ISuck
{
public FileStream Munge(ICollection collection);
public NetworkStream Munge(IEnumerable enumerable);
public MemoryStream Munge(Hashtable ht);
public Stream Munge(ICloneable cloneable);
public object Munge(object o);
public Stream Munge(IDictionary dic);
}
Good luck trying to unravel this mystery without going insane.
Of course, all of this is moot if you assert that interface implementations should only support return-type variance and not argument-type variance. But almost everyone would consider such a half-implementation to be completely broken and start spamming bug reports, so I don't think that the C# team is going to do it.
I don't know if this is the official reason why it's not supported in C# today, but it should serve as a good example of the kind of "write-only" code that it could lead to, and part of the C# team's design philosophy is to try to prevent developers from writing awful code.
You have to implement an interface's methods exactly as they are in the interface. ICloneable's Clone method returns an object, so your SomeClass must also return an object. You can, however, return a SomeClass instance in SomeClass's Clone method without any problem, but the method definition must match the interface:
public class SomeClass: IClonable
{
// Some Code
//Implementing interface method
Public object Clone()
{
SomeClass ret = new SomeClass();
// copy date from this instance to ret
return ret;
}
}
In terms of explaining the reasons behind C# decisions, Eric Lippert from Microsoft has written much explaining Contra/CoVariance in C#... here's the tag list from his blog:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
[Edit]
Specific to your question, this might be the right post.. http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx
It looks like the kind of thing they could have used generics for, but it seems there is a good reason why they did not.
It is talked about here:
http://bytes.com/topic/c-sharp/answers/469671-generic-icloneable
Basically, a generic interface that would allow:
public class MyClass : IClonable<MyClass>
would also allow:
public class MyClass : IClonable<MyOtherClass>
which doesn’t really provide any benefit, and might confuse things.
According to the C# specification, you must use a method with an identical signature when overriding or implementing an interface method. Keep in mind that Microsoft does not own C#. Their C# compiler is simply their implementation of it. So why would the spec do things this way? I can only guess, but I suspect it was for ease of implementation.

ReadOnlyCollection vs Liskov - How to correctly model immutable representations of a mutable collection

Liskov-substitution principle requires that subtypes must satisfy the contracts of super-types. In my understanding, this would entail that ReadOnlyCollection<T> violates Liskov. ICollection<T>'s contract exposes Add and Remove operations, but the read only subtype does not satisfy this contract. For example,
IList<object> collection = new List<object>();
collection = new System.Collections.ObjectModel.ReadOnlyCollection<object>(collection);
collection.Add(new object());
-- not supported exception
There is clearly a need for immutable collections. Is there something broken about .NET's way of modeling them? What would be the better way to do it? IEnumerable<T> does a good job of exposing a collection while, at least, appearing to be immutable. However, the semantics are very different, primarily because IEnumerable doesn't explicitly expose any of state.
In my particular case, I am trying to build an immutable DAG class to support an FSM. I will obviously need AddNode / AddEdge methods at the beginning but I don't want it to be possible to change the state machine once it is already running. I'm having difficulty representing the similarity between the immutable and mutable representations of the DAG.
Right now, my design involves using a DAG Builder up front, and then creating the immutable graph once, at which point it is no longer editable. The only common interface between the Builder and the concrete immutable DAG is an Accept(IVisitor visitor). I'm concerned that this may be over-engineered / too abstract in the face of possibly simpler options. At the same time, I'm having trouble accepting that I can expose methods on the my graph interface that may throw NotSupportedException if the client gets a particular implementation. What is the right way to handle this?
You could always have a (read-only) graph interface, and extend it with a read/write modifiable-graph interface:
public interface IDirectedAcyclicGraph
{
int GetNodeCount();
bool GetConnected(int from, int to);
}
public interface IModifiableDAG : IDirectedAcyclicGraph
{
void SetNodeCount(int nodeCount);
void SetConnected(int from, int to, bool connected);
}
(I can't figure out how to split these methods into get/set halves of a property.)
// Rubbish implementation
public class ConcreteModifiableDAG : IModifiableDAG
{
private int nodeCount;
private Dictionary<int, Dictionary<int, bool>> connections;
public void SetNodeCount(int nodeCount) {
this.nodeCount = nodeCount;
}
public void SetConnected(int from, int to, bool connected) {
connections[from][to] = connected;
}
public int GetNodeCount() {
return nodeCount;
}
public bool GetConnected(int from, int to) {
return connections[from][to];
}
}
// Create graph
IModifiableDAG mdag = new ConcreteModifiableDAG();
mdag.SetNodeCount(5);
mdag.SetConnected(1, 5, true);
// Pass fixed graph
IDirectedAcyclicGraph dag = (IDirectedAcyclicGraph)mdag;
dag.SetNodeCount(5); // Doesn't exist
dag.SetConnected(1, 5, true); // Doesn't exist
This is what I wish Microsoft had done with their read-only collection classes - made one interface for get-count, get-by-index behaviour etc., and extend it with an interface to add, change values etc.
I don't think that your current solution with the builder is overengineered.
It solves two problems:
Violation of LSP
You have an editable interface whose implementations will never throw NotSupportedExceptions on AddNode / AddEdge and you have a non-editable interface that doesn't have these methods at all.
Temporal coupling
If you would go with one interface instead of two, that one interface would need to somehow support the "initialization phase" and the "immutable phase", most likely by some methods marking the start and possibly end of those phases.
Read only collections in .Net do not go against LSP.
You seem bothered by the read only collection throwing a not supported exception if the add method is called, but there is nothing exceptional about it.
A lot of classes represent domain objects that can be in one of several states and not every operation is valid in all states: streams can only be opened once, windows cannot be shown after they are disposed, etc..
Throwing exceptions in those cases is valid as long as there is a way to test the current state and avoid the exceptions.
The .Net collections were engineered to support the states: read-only and read/write. Which is why the method IsReadWrite is present. It allows callers to test the state of the collection and avoid exceptions.
LSP requires subtypes to honor the contract of the super type, but a contract is more than just a list of methods; it is a list of inputs and expected behavior based on the state of the object:
"If you give me this input, when I'm in this state expect this to happen."
ReadOnlyCollection fully honors the contract of ICollection by throwing a not supported exception when the state of the collection is read only. See the exceptions section in the ICollection documentation.
You can use explict interface implementations to separate your modification methods from the operations needed in the read-only version. Also on your read-only implementation have a method that takes a method as an argument. This allows you to isolate your building of the DAC from the navigation and querying. see the code below and its comments:
// your read only operations and the
// method that allows for building
public interface IDac<T>
{
IDac<T> Build(Action<IModifiableDac<T>> f);
// other navigation methods
}
// modifiable operations, its still an IDac<T>
public interface IModifiableDac<T> : IDac<T>
{
void AddEdge(T item);
IModifiableDac<T> CreateChildNode();
}
// implementation explicitly implements IModifableDac<T> so
// accidental calling of modification methods won't happen
// (an explicit cast to IModifiable<T> is required)
public class Dac<T> : IDac<T>, IModifiableDac<T>
{
public IDac<T> Build(Action<IModifiableDac<T>> f)
{
f(this);
return this;
}
void IModifiableDac<T>.AddEdge(T item)
{
throw new NotImplementedException();
}
public IModifiableDac<T> CreateChildNode() {
// crate, add, child and return it
throw new NotImplementedException();
}
public void DoStuff() { }
}
public class DacConsumer
{
public void Foo()
{
var dac = new Dac<int>();
// build your graph
var newDac = dac.Build(m => {
m.AddEdge(1);
var node = m.CreateChildNode();
node.AddEdge(2);
//etc.
});
// now do what ever you want, IDac<T> does not have modification methods
newDac.DoStuff();
}
}
From this code, the user can only call Build(Action<IModifiable<T>> m) to get access to a modifiable version. and the method call returns an immutable one. There is no way to access it as IModifiable<T> without an intentional explicit cast, which isn't defined in the contract for your object.
The way I like it (but maybe that's just me), is to have the reading methods in an interface and the editing methods in the class itself. For your DAG, it is highly unlikely that you will have multiple implementations of the data structure, so having an interface to edit the graph is kind of an overkill and usually not very pretty.
I find having the class representing the data-structure and the interface being the reading structure pretty clean.
for instance:
public interface IDAG<out T>
{
public int NodeCount { get; }
public bool AreConnected(int from, int to);
public T GetItem(int node);
}
public class DAG<T> : IDAG<T>
{
public void SetCount(...) {...}
public void SetEdge(...) {...}
public int NodeCount { get {...} }
public bool AreConnected(...) {...}
public T GetItem(...) {...}
}
Then, when you require editing the structure, you pass the class, if you just need the readonly structure, pass the interface. It's a fake 'read-only' because you can always cast as the class, but read-only is never real anyway...
This allows you to have more complex reading structure. As in Linq, you can then extend your reading structure with extension methods defined on the interface. For instance:
public static class IDAGExtensions
{
public static List<T> FindPathBetween(this IDAG<T> dag, int from, int to)
{
// Use backtracking to determine if a path exists between `from` and `to`
}
public static IDAG<U> Cast<U>(this IDAG<T> dag)
{
// Create a wrapper for the DAG class that casts all T outputs as U
}
}
This is extremely useful to separate the definition of the datastructure from 'what you can do with it'.
The other thing that this structure allows is to set the generic type as out T. That allows you to have contravariance of argument types.
I like the idea of designing my data structures immutable in the first place. Sometimes it's just not feasible but there's a way to accomplish this quite often.
For your DAG you most probably have some data structure in a file or a user interface and you could pass all the nodes and edges as IEnumerables to your immutable DAG class' constructor. Then you can use the Linq methods to transform your source data to nodes and edges.
The constructor (or a factory method) can then build the class' private structures in a way that's efficient for your algorithm and do upfront data validations like acyclicy.
This solution distinguishes from the builder pattern in a way that iterative construction of the data structure is not possible but often that's not really required.
Personally, I don't like the solutions with separate interfaces for read and read/write access implemented by the same class because the write functionality is not really hidden... casting the instance to the read/write interface exposes the mutating methods. The better solution in such a scenario is having an AsReadOnly method that creates a really immutable data structure copying the data.

System.Exception.Data Property

The System.Exception class (actually any exception) has Data property which is almost always empty. While throwing exceptions, should this field be of any use? Or does it have some internal use that I am not aware of?
The documentation seems clear enough as to its use (emphasis added):
Gets a collection of key/value pairs that provide additional user-defined information about the exception.
Why does it exist in the first place? I assume it's the same reason Control has a Tag property. In the early days of .NET (before every Bob and Betty programmer understood objects and inheritance) they wanted to make the API simple enough that everyone could figure out how to add extra data to things.
However, the point of creating custom exceptions that derive from System.Exception is not necessarily to include additional information, but to make it possible for the client to limit the exceptions they catch to only those that they can handle. If they know how to handle a set of defined exceptions that your code can throw, they should be able to only catch those exceptions, without having to catch the base System.Exception class. What you should definitely never do is require the client code to catch a non-specific exception class and read a property to determine what type of exception it is (and thus whether or not they are able to handle it).
I've honestly never used this property before. I had to check the documentation to even see that it did indeed exist. But I imagine it's most useful for implementing custom exception logging. You can embed a lot of important information into the Data property (regardless of the level of derivation of exception class), and then pass that off to your logging code. Reflector indicates that it's used internally in a handful of places for precisely that purpose. It's also nice that all the information you provide here gets correctly serialized for you automatically.
Another note here, what I do when I inherit an exception and add properties, is to make the properties actually get and set from the data dictionary, and not from local variables.
[Serializable]
public class PacketParseException : Exception
{
public byte[] ByteData
{
get
{
return (byte[])this.Data["ByteData"];
}
}
public PacketParseException(string message, byte[] data, Exception inner) : base(message, inner)
{
this.Data.Add("ByteData", data);
}
}
The way I see it, then the internal data is available from an Exception as well, for example when logging, so no need to cast to actual type.
With the new CallerMemberNameAttribute it's even easier to use the Data property for storage:
public class BetterException : Exception
{
protected T GetValue<T>([CallerMemberNameAttribute] string propertyName = "")
{
return (T)Data[propertyName];
}
protected void SetValue<T>(T value, [CallerMemberNameAttribute] string propertyName = "")
{
Data[propertyName] = value;
}
}
Usage:
class MyException : BetterException
{
public MyException(string name)
{
Name = name;
}
public string Name
{
get { return GetValue<string>(); }
set { SetValue(value); }
}
}

Explicit implementation of interface's GetEnumerator causes stack overflow

I'm doing my best to code against interfaces whenever possible, but I'm having some issues when it comes to collections. For example, here are a couple interfaces I'd like to use.
public interface IThing {}
public interface IThings : IEnumerable<IThing> {}
Here are the implementations. In order to implement IEnumerable<IThing> I need to explicitly implement IEnumerable<IThing>.GetEnumerator() in Things.
public class Thing : IThing {}
public class Things : List<Thing>, IThings
{
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
// This calls itself over and over
return this.Cast<IThing>().GetEnumerator();
}
}
The problem is that the GetEnumerator implementation causes a stack overflow. It calls itself over and over again. I can't figure out why it'd decide to call that implementation of GetEnumerator instead of the implementation provided by the result of this.Cast<IThing>(). Any ideas what I'm doing wrong? I'm willing to bet it's something extremely silly...
Here's some simple test code for the above classes:
static void Enumerate(IThings things)
{
foreach (IThing thing in things)
{
Console.WriteLine("You'll never get here.");
}
}
static void Main()
{
Things things = new Things();
things.Add(new Thing());
Enumerate(things);
}
Use this instead:
public class Things : List<Thing>, IThings
{
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
foreach (Thing t in this)
{
yield return t;
}
}
}
Or you could work with containment instead.
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
// This calls itself over and over
return this.Cast<IThing>().GetEnumerator();
}
It's a recursive call with no break condition, you're going to get a stack overflow, because it's going to very quickly fill up the stack.
You're casting to an interface, which does not do what you think it does. In the end you are just calling this.GetEnumerator(); which is the function you're already in, thus recursing. Perhaps you mean base.GetEnumerator();
Generally, you would probably want to decouple the implementation of the Things collection from the implementation of the Thing object. The Things class is capable of working with any implementation of IThing, not just the Thing class.
Specifically:
public class Things : List<IThing>, IThings
{
}
In this case, you don't have to override the default implementation of GetEnumerator(), the base implementation is already typed correctly for you. This will avoid the overflow that you're currently experiencing and satisfies the test case you provided.
This is a nice example of the need for the language and runtime to understand covariance and contravariance.
In C# 4, you can just use
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
return base.GetEnumerator();
}
Seems pretty obvious that this.Cast<IThing>() returns an IEnumerable. Or, at least it does without the implementation of Cast.
I don't know if a question qualifies as an answer but bear with me Im a consultant ;P Why do you wanna implement the GetEnumerator()?
You're deriving from List if you change that to List you get the GetEnumerator for free.
Be aware too that deriving from List is generally a bad idea. you should consider deriving from IEnumerable<()IThings> (as you're already doing which is atm superflurous since List also implements that interface) or if you need the List interface and not only the IEnumerable implement IList and keep a private List object. That way you get full control about the implementation and only expose a design contract (through the implemented interfaces)

Is it ok to use the same interface definition but provide different behaviour?

the summary of my question is "I have 2 classes which share a common interface, however the two classes have different behaviour with regard to their properties. One interface throws an exception if the parameter values are invalid the other updates its internal state to handle the invalid values. Is it okay for the two classes to share the same interface or should two interfaces be defined to indicate to the developer that the two have different behaviours?"
I'll try to clarify with some code. I have the interface defind below.
public interface IStationDictionary
{
bool this[string stationId] { get; set; }
}
And a class that implements the interface, this class is used to set the output port on a digital IO board.
public class DigitalStationAdapter : IStationDictionary
{
public bool this[string stationId]
{
get { return ports[stationId].Value; }
set { ports[stationId].Value = value; }
}
public void AddDigitalStation(string stationId, DigitalIoPort port)
{
ports.Add(stationId, port);
}
private IDictionary<string, DigitalIoPort> ports = new Dictionary<string, DigitalIoPort>();
}
I also have a classes that records which stations have had values changed so that those changes can be propegated to the digital IO.
public class StationTransitions : IStationDictionary
{
public bool this[string stationId]
{
get
{
bool result = false;
if(changes.ContainsKey(stationId))
result = changes[stationId];
return result;
}
set
{
if(!changes.ContainsKey(stationId))
changes.Add(stationId, value);
else
changes[stationId] = value;
}
}
public IDictionary GetChanges()
{
IDictionary<string, bool> result = changes;
changes = new Dictionary<string, bool>
return result;
}
private IDictionary<string, bool> changes = new Dictionary<string, bool>();
}
So, while both classes implement the same interface DigitalStationAdapter will throw a KeyNotFoundException if you try to access the indexer with a stationId not in the dictionary. Whereas, StationTransitions will succeed, i.e. different behaviour. Is this okay, I thought that interfaces are used to define behaviour as well as structure?
Keith.
This is fine. Think of it this way: The key to determining whether any inheritance relationship is "ok" is the Liskov substitution principle. This requires that code expecting a base class should be able to use a derived class without knowing it. This implies that preconditions for a method cannot be strengthened in a derived class but can be weakened. Interfaces are just a special case of base classes.
In your case, the interface's implicit precondition would be that input be valid as you define it. All code that expects the base class should assume this precondition and avoid passing invalid data or be prepared to deal with the exception. In the concrete class that updates its internal state to deal with the invalid input, you are weakening a precondition. This is acceptable as far as the Liskov substitution principle goes.
On the other hand, if you were to make the class that automatically deals with the invalid input w/o throwing a base class, and make the class that throws a descendant, this would be bad, because code expecting the base class could not use the derived class as if it were the base class. It would have to know about the derived class to deal with the possible exception.
I propose two angles to judge if implementations differ too much:
Writing documentation.
In this case I think it would be hard to write a single piece of documentation (on the interface) that describes the behavior because the implementations are so different (one throws, the other don't).
How likely is it that swapping implementations will introduce a bug?
In this case I would argue that the probability is non-trivial.
Using these two angles I believe the difference is too big and:
If you prioritize risk then the class that currently throw should stop throwing (and check for presence of key).
If you're OK with extra testing and want to have the strict contract then you could make the less strict class more strict.
If you cannot change the classes, I propose having two interfaces.

Categories

Resources