Abstract class: Which exception should be thrown when child classes are not implemented correctly?

Let's say I have an abstract class:

abstract class MyAbstract { protected abstract object ImplementMePlz(); public object DoSomething() { // Some logic here var result = ImplementMePlz(); if (result == null) throw new YourChildClassIsStupidException("ImplementMePlz() should never return null."); return result; } } 

What exception should I use in this scenario? Is there an assigned exception in the .NET Framework or should I create my own custom exception?

+4
source share
3 answers

The answer to the question "Is there an assigned exception in the .NET Framework?" โ€œnoโ€ - there is no such exception.

If I were you, I would create a custom exception.

+4
source

You must create your own exception class. There is no exception to the framework that I know of in order to deal with this situation. What for? I do not think that the structure needs this exception.

In addition, I would suggest using Code Contracts to prevent exclusion in the first place.

+1
source

It depends on why your child class returned null. It might make more sense to throw an exception in the child class, since it will have a better idea why it returns null and can throw a more informative exception.

If you do not have control over the child class, you must do one of two things.

  • You can print some information from zero return. You must create an exception that passes this knowledge, for example. The API states that you must return null, if one of your inputs is invalid, print InvalidArgumentExpection.

  • You just know that it should not be null if it throws an ArgumentNull exception or something like that

0
source

Source: https://habr.com/ru/post/1402959/


All Articles