1

I want to create an error message in Python, i.e. the program should be interrupted and an (if possible coloured) error message should be printed. For instance:

If a == 0:

Error("a should be nonzero")

In Matlab, you can do this using the error instruction. How can you do this in Python? I have found this page but I am not sure that is what I am looking for.

Karlo
  • 1,630
  • 4
  • 33
  • 57

1 Answers1

1

You can raise it like so:

if a == 0:
    raise ValueError("a should be nonzero")

or simply by using assert as:

assert a!=0, "a should be nonzero!"
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 5
    Not my downvote, but don't think `assert` should be used on user input, vaguely relevant http://stackoverflow.com/a/945135/6260170 – Chris_Rands Feb 27 '17 at 15:53
  • 1
    Yeah, asserts are for catching broken program logic, not bad data. If the user sees an AssertionError they are entitled to tell you to fix the program. – PM 2Ring Feb 27 '17 at 15:59
  • OTOH, `a` may not be user data but the result of an internal calculation that cannot possibly result in zero if the program logic is correct. And in that situation `assert` is definitely appropriate. – PM 2Ring Feb 27 '17 at 16:06
  • @PM2Ring Yes, I agree, when I made the comment, `a` was user input: http://stackoverflow.com/posts/42489906/revisions – Chris_Rands Feb 27 '17 at 16:43
  • 1
    @Chris Indeed. But we don't know what it is in the OP's code. – PM 2Ring Feb 27 '17 at 16:49