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

In .net, C #

There are many Exception subclasses that already exist, what are they and when do we use them instead of creating our own subclass?

This question is duplicated C # has an overview of exceptions

+3
source share
3 answers

Here is a list of common exception types. If you want to know when to create your own exceptions, try:

What are some guidelines for creating your own custom exception?

+5
source

, , (, NullReferenceException IndexOutOfRangeException) - ; , .

, , .

ArgumentNullException

: , , null, null .

ArgumentOutOfRangeException

, , .

, , , . , ,

if (x < 1)
{
    throw new ArgumentOutOfRangeException("x");
}

.

FormatException

, , , , , .

InvalidOperationException

(, ), , . , - , .

IEnumerator<T> InvalidOperationException, , . , , , .

NotSupportedException

, abstract.

"" , . :

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
    }
}

, ( ) ; , , .

+10
-1

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


All Articles