Asara
Asara

Reputation: 3394

Should I use exceptions to solve bad user input?

I always learned, that exceptions should only be thrown in real exceptional cases and not be used for expectable error cases. But in Exception Handling tutorial I found this example:

def do_stuff_with_number(n):
          print(n)

  the_list = (1, 2, 3, 4, 5)

  for i in range(20):
      try:
          do_stuff_with_number(the_list[i])
      except IndexError: # Raised when accessing a non-existing index of a list
          do_stuff_with_number(0)

Here is an exception used to validate and solve a user input error. Isn't that a very bad example for exceptions? Or are there cases in which it is good to use it this way?

Upvotes: 0

Views: 343

Answers (3)

Matteo A
Matteo A

Reputation: 358

It's not "a very bad" example. Exception are meant to raise the attention on something that should not occur, such as accessing a non-existent value.

The only thing that I could argue is the way the exception is handled. Why call the same function but with a 0 default parameter? What if the_list itself (side note: it's a tuple, not a list!) contains 0? And what if the element exists but is unexpected?

As a general role, do not let the program fail for you: if you know in a particular point that something is not ok, throw an error! The caller should always catch that error and deal with it doing something useful. Finally, be aware that the try is inside a for loop, meaning that you don't care if some tuple value (or all) could not be processed by do_stuff_with_number() function. A situation like this in my opinion could be handled with ifs while looping the_list.

Upvotes: 0

Lcat
Lcat

Reputation: 929

Exceptions are a good way to handle the unexpected. While this form is fine, in a production setting, it is a good idea to deal more explicitly with the most common exceptions

Upvotes: 0

Reid Jordan
Reid Jordan

Reputation: 9

Exceptions are a great way to go in most errors as they are mostly used to immediately terminate the program. In regards to user input, it might just be easier to re-ask the user for another input.

Upvotes: 1

Related Questions