So, I've got a situation where I need to throw an exception because "an argument is not supported". To explain how I got here, this is the rough situation:
- Ooks come in many types, including Yooks and Zooks
- Ooks can befriend other Ooks, but only of the right types
- Yooks can befriend Zooks, but Zooks cannot befriend Yooks
Code example:
public abstract class Ook
{
public abstract bool TryBefriendYook(Yook yook);
public abstract bool TryBefriendZook(Zook zook);
public bool TryBefriend(Ook o0k)
{
Type ookType = ook.GetType;
if (ookType == typeof(Yook))
{
TryBefriendYook((Yook)ook);
return true;
}
else if (ookType == typeof(Zook))
{
TryBefriendZook((Zook)ook);
return true;
}
else return false;
}
public void Befriend(Ook ook)
{
if(!TryBefriend(ook))
throw new Exception(
"argument type not supported");
}
}
public sealed class Yook : Ook
{
public override bool TryBefriendYook(Yook yook)
{
return true;
}
public override bool TryBefriendZook(Zook zook)
{
return true;
}
}
public partial sealed class Zook : Ook
{
public override bool TryBefriendYook(Yook yook)
{
return false;
}
public override bool TryBefriendZook(Zook zook)
{
return true;
}
}
So, this kind of falls under both ArgumentException (the argument isn't right for the subclass) and NotSupportedException (the subclass doesn't accept the argument), doesn't it?
So, which one should I choose - or should I write a custom exception for this situation instead?
According to MSDN:
So according to MSDN, ArgumentException is more suitable to your case edit: if there is absolutely need for more arguments or custom return you can write your own custom exception however there is no problem in using the ArgumentException if it fits your needs.