Reject Negative Numbers as exceptions in Python

31,706

Solution 1

The "prefer try/except" thing is a guideline, not a hard and fast rule. In this case, it doesn't make any sense, as you've discovered. You should use if choice < 0: like normal.

In general there are three reasons to prefer try/except, none of which apply here.

  1. If you're doing multiple operations in sequence, each of which can fail, and you don't care which one fails. In this case, you'd use a try block around the entire sequence of code, simplifying things.
  2. If you expect callers to use user defined types with a duck-typed interface that don't implement any particular superclass or abstract base class. This is primarily a concern when writing library code.
  3. If you expect the operation to usually succeed, and it throws an exception on failure. In this case, try/except will normally be faster.

As a side note, the main reason why "prefer try/except" is emphasized to new Python programmers is that many programmers come from languages where exceptions are slow or nonexistent, making them biased against using them, even when appropriate.

Solution 2

Say, you want to print only positive numbers and if the number is negative you raise an exception

a = int(raw_input())
if a < 0:
    myError = ValueError('a should be a positive number')
    raise myError
print(a)

Solution 3

try: 
  choice = int(input('Enter a number: '))
  assert choice > 0 # Test if it true
except AssertionError :
  print("Number is negative")
Share:
31,706
Mark Puchala II
Author by

Mark Puchala II

Finishing a Bachelor's of Computer Science to refine my software development process. Currently brushing up on React.

Updated on July 17, 2022

Comments

  • Mark Puchala II
    Mark Puchala II almost 2 years

    I'm trying to run a basic prompt that takes a number, then runs a recursive function on it.

    Any negative number causes a recursion error, for the function being unable to handle them.

    Now, I've learned with Python that situations like this call for a "try/except" model. Here's what I came up with:

    try: 
      choice = int(input('Enter a number: '))
      INSERT RECURSIVE FUNCTION HERE
    except RecursionError as err:
      print('Error: ', str(err))
    

    This exception doesn't work, as it still shows the entire recursive process in red lines, with my exception only replacing the final line. I know I could easily solve this by logic, for example:

    if choice < 0:
      print("Error: Bro, We don't take no Negative Numbers around here.")
    

    However, I was taught we generally want to avoid "solving errors by Logic" in Python, instead working via the "try/except" model.

    What could I do to reject negative numbers via a "try/except" model instead of an "if/else"?

    If you can help me understand a way to make this react to ValueError, that'd be another great help.

  • Mark Puchala II
    Mark Puchala II over 8 years
    This definitely answered a great deal for me. Is there a way to run a simple "assert" with a single line to report any errors instead of an entire traceback report?
  • Antimony
    Antimony over 8 years
    @Mark The assert statement will throw an AssertionError if the argument is false (and python is run without the -O or -O2 arguments). If you want to hide the stacktrack, you can just catch the exception instead of letting it propagate to the top level. But I'm not sure why you'd want to do that.