4

What's the point of throwing exceptions? For example I stumbled across this:

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

But when you don't throw the nullpointer, you'll also get a nullpointer? I see this regularly and I wanted to know if this is a good habit to learn?

SJ19
  • 1,933
  • 6
  • 35
  • 68

5 Answers5

1

It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.

John Paul
  • 827
  • 2
  • 6
  • 16
0

The idea behind the THROW is to prevent the error from stopping your program.

If it's a fatal enough error, your program will stop anyway. But if the program can continue it will, and just let you know that an error occurred.

In many cases, you assign a function to report the error, since you threw it up and know what it is.

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
0

I always found throwing exceptions to be a matter of design and readability. For example, generally when I design something I prefer to handle errors where they occur. However an equally valid design would be to throw the exception and handle it somewhere else. I have seen some abstractions where generally your flow is something similar to this...

FlowControl -> GenericMethod(catches exceptions and calls methods only) -> PrivateMethods (generally used to do the work, throws exceptions).

You might find a more complete answer here as well: When to catch the Exception vs When to throw the Exceptions?

Community
  • 1
  • 1
Sh4d0wsPlyr
  • 948
  • 12
  • 28
0

It's possible that the rest of your method will not throw the exception and will instead have some kind of undesirable behavior if you use a null pointer. In your example, if it's basically a "ToList" wrapper, it might be implemented as:

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

Instead of throwing, this will simply return an empty list (if I recall correctly at least, I don't think C# throws on null lists used in foreach). As such, you'll need to include an explicit null check and throw to get your desired behavior.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
0

Throwing specific exception means that your application has faced something it shouldn't have. It can be either invalid argument(when someone passes null and current method cannot work with value of null), invalid field state(its value has been changed to some value, which is forbidden for instance current state) and many many more.

Basically when you throw exceptions in a good manner, each person using your e.g. library can preserve its correct flow.

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29