Should the method ignore illegal input or throw an exception?

If a method checks its input and detects an invalid input, what should it do: raise an exception (or use a different error mechanism) or do nothing / ignore incorrect input?

In Java, the HashTable class throws a NullPointerException if null references are specified as a parameter. This is sometimes annoying, but I think it can have advantages because errors are caught early. Some other methods ignore illegal input without doing anything. This is less annoying and usually nothing bad happens, but there may be cases, then this behavior causes headaches - or not?

I'm not sure which way is better. Therefore, I ask you: what do you think about this issue?

+3
source share
5 answers

Define an exception throw. Exceptions are annoying to make you do something with them.

Think of it this way if your program does nothing with bad input, how should you tell the user that nothing happened and why? Also, how long will it take you to debug a program that does nothing with errors?

+8
source

I think it depends on the context or level of abstraction you are working on. The most important thing is to be consistent. If you throw exceptions at this level, go ahead and throw your exception. If not, check how the layer behaves and what it does.

+4
source

, .

, , , , , , . , , , , .

- (, 0 - 100, -10, , , 0 ).

, , , .

+2

, , , ?

, .

  • ( - , )
  • , .

, , , .

.

- . , .

,

-R

+2

Fail Fast : Never ignore incorrect input. You can hide the problem and make them very difficult to find.

Some of them come very close to Design by Contract (DBC).

Follow the recommendations that are already used in your project or in your company, or define them now.

+1
source

All Articles