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.

6
  • 2
    just raise an error Commented Feb 27, 2017 at 15:46
  • This solved my question. I knew that it was a very basic one. I had not found the duplicate question myself. Can I delete my question? Commented Feb 27, 2017 at 15:56
  • 1
    You might as well leave your question - it can act as a portal to the linked question. Commented Feb 27, 2017 at 16:01
  • @PM2Ring Yes but I will continue to lose reputation as people downvote. Commented Feb 27, 2017 at 16:03
  • On the other hand, you cannot close too many questions... Commented Feb 28, 2017 at 13:18

1 Answer 1

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!"
Sign up to request clarification or add additional context in comments.

5 Comments

Not my downvote, but don't think assert should be used on user input, vaguely relevant stackoverflow.com/a/945135/6260170
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.
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.
@PM2Ring Yes, I agree, when I made the comment, a was user input: stackoverflow.com/posts/42489906/revisions
@Chris Indeed. But we don't know what it is in the OP's code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.