2

I want to check a group of input, and if any one of them is illegal, I throw a error and make a warning, so I want to make the warning more customed to figure out which one is wrong.

try:
    assert input1<1 something like this, "input1 error xxx"
    assert input2 xxx, "input2 error xxx"
    xxxx
except AssertionError:
   make a warning dialog using the assert infomation
except:
   pass
else:
   pass

Is it possible? I think I can avoid multiple try-except blocks or if blocks, is there a pythonic way to do it? Thank you in advance.

Get it. Thank you for your help. Assert should not use for test. I will modify my code now.

ljy
  • 143
  • 1
  • 10
  • 1
    Possible duplicate of [Making Python's \`assert\` throw an exception that I choose](http://stackoverflow.com/questions/1569049/making-pythons-assert-throw-an-exception-that-i-choose) – Chris Apr 18 '17 at 14:25
  • 1
    Just `raise` an exception yourself; `assert` should not be applied to inputs anyway http://stackoverflow.com/a/945135/6260170 – Chris_Rands Apr 18 '17 at 14:27

2 Answers2

3

Catch the exception and turn it into a string:

try:
    assert False, 'Foo'
except AssertionError as e:
    message = str(e)  # 'Foo'
    print(message)

Having said this, asserts can be disabled with a flag and should not be used for necessary conditions, only for debugging sanity checks. You should be raising a more specific, custom exception yourself.

deceze
  • 510,633
  • 85
  • 743
  • 889
3

Why don't you try to make your own custom Exception and throw it whenever your condition fails. Then you can catch it. The beauty of this is even if your code is throwing some internal error you would know what to do with it.

class MyException(Exception):
    pass

....

try:
    #if some condition
    raise MyException()
except MyException:
    #handle this exception

or since you are handling test cases

def mytest(self):
    with self.assertRaises(MyException):
        #some if condition
        raise MyException()
Pansul Bhatt
  • 384
  • 2
  • 5