1

This is an interview question, it has been done.

Which of the following circumstances should throw Exceptions? Explain your reasoning.

(1) Someone tries to set the capacity of a PackingBox to a negative value.

(2) A syntax error is found in a configuration file that an object uses to set its initial state.

(3)A method that searches for a programmer-specified word in a string array cannot find any occurrence of the word.

from When and how should I use exception handling?

" But if you get some invalid data from inside your very own program - don't throw an exception. If your problem comes from your own bad code, it's better to use ASSERTs to guard against it. Exception handling is needed to identify problems that program cannot handle and tell them about the user, because user can handle them. "

I think : (1) should use exception, because the input is from users. The error is not generated from the inside of the program.

(2) and (3) should not use exceptions because they are from the the inside of the program. And, the users cannot help that. So, we should use "assert" or "if" branch to handle the errors by the program itself.

Right ?

Any help is appreciated.

thanks !

Community
  • 1
  • 1
user1000107
  • 405
  • 7
  • 14

1 Answers1

3

(1) Someone tries to set the capacity of a PackingBox to a negative value.

That's a programming error, it should fire an assert but not an exception. It's simply a bug in the code. If the negative value comes from user input, then the error is not validating it.

(2) A syntax error is found in a configuration file that an object uses to set its initial state.

That's an exceptional situation.

(3)A method that searches for a programmer-specified word in a string array cannot find any occurrence of the word.

That's not an exceptional situation, no matches found is an expected result.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Note particularly for the last case, it's not an either-or. You can have both. Depending on the requirements of the case at hand (rather unspecified here!) one or the other is typically far more convenient. – Cheers and hth. - Alf May 18 '12 at 01:35
  • for (1), if it is from an user, we should pop a warning to show that the input must be non-negative. what is meaning of "the error is not validating it." ? thanks – user1000107 May 18 '12 at 02:27
  • Means not validating user input is a programming error, no different than directly calling that function with a negative value. When validating user input, invalid input is not an exceptional situation so the user should be warned but it does not grant raising an exception. – K-ballo May 18 '12 at 02:28
  • @K-ballo, thanks, for (3), why it is an exception ? because an error config file is an external problem that cannot be handled by the program itself so that the user must take care of it ? thanks – user1000107 May 18 '12 at 03:42