Example code:
public class ElementList
{
// some code...
public ElementList (Element owner)
{
// some code...
}
public void Add (Element e)
{
if (e == owner) // cannot add child which will be self-parent
{
throw new SomeException (); // main problem here
}
childList.Add (e);
}
}
Now what kind of exception I should throw? And if you suggest custom exception, please tell me a good name for it.
In short:
ArgumentExceptionwill do the trick. However, it is not a good practice to throw exceptions that you may easily managed in your code.I would suggest to rewrite your code like:
However, if you would like to proceed with exception scenario, then the code will probably look like:
Edit: As a reference you may of course use the MSDN article for detailed understanding.