.net exceptions

When should I create my own custom exception class and not use the one provided by .Net?

What base exception class should I get and why?

+3
source share
6 answers

Why create your own exception?

You create your own exception so that when you throw it, you can have certain catches and therefore distinguish them from excluded (unhandled) exceptions from the system.

What class should you learn from this?

ApplicationException, MS , System.Exception, ApplicationException

+6

, , . , .

, , . , 0 < x < 4000.

private string ToRoman(int number)
{
    if (number > 0 && number < 4000)
    {
        //ConvertHere
    }
    else
    {
        //Custom exception used for readability purposes.
        throw new NumeralOutOfRangeException();
    }
}

, Microsoft , Exception. (http://msdn.microsoft.com/en-us/library/seyhszts.aspx)

+2

, , . , .

public class MyLibraryException : Exception
{
    // .....
}

, .

public class SomethingHorribleException : MyLibraryException 
{
    // .....
}

, -, MyLibraryException.

+2

. :

try {
// do stuff
} catch (MyCustomException e) {
// handle this known exception
}

.

+1

, :

, , .

. , SQLException. . (, XML, ..), .

, UI- .

+1

I would create my own excpetion class if I wanted to add other properties to it, such as variables, location, username, num returned entries, etc.

Essentially, I would create a class that would narrow what error is and how to recreate it.

change

oh, and you can add validation errors to the exception class, which can be brought to the forefront to show errors.

0
source

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


All Articles