Exception throwing point

What is the point of throwing exceptions? For example, I came across this:

static List<Integer> list(int [] a) {
    if (a == null)
        throw new NullPointerException();
        //...

But when you don't drop nullpointer, will you also get nullpointer? I see it regularly, and I would like to know if it is good to study?

+4
source share
5 answers

Better to fail quickly. For example, a function can do a bunch of stuff before it even refers to the variable "a" in your example, which leads to a lot of unnecessary processing. It would be best to crash right away if you know that "a" is null from the very beginning. You can also add a special error message to the exception.

+1

THROW , .

, . , , .

, , .

0

, . , , -, , . - . , ...

FlowControlGenericMethod ( ) → PrivateMethods ( , ).

: Exception vs ?

0

, - , . , "ToList", :

static List<Integer> list(int[] a)
{
    List<int> ret = new List<int>();
    foreach (int i in a)
        ret.add(i);
    return ret;
}

, , ( , , , # , foreach). , throw, .

0

, -, . ( - null, null), ( , ) .

Basically, when you arbitrarily throw exceptions, each person using your library, for example, can save the correct thread.

0
source

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


All Articles