Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pythonic way of raising an error within the try block

I have a method that checks something and which can

  • raise an exception itself
  • return True
  • return False

I want catch the exception properly to raise one myself, but also if the test returns False. The incorrect way to do this is

try:
    if not check():
        raise MyException()
except:
    raise MyException()

as the first MyException is caught after the except again. One way to handle this properly would be

try:
    flag = check()
except:
    raise MyException()
else:
    if not flag:
        raise MyException()

Is this the only way of dealing with this situation, or is there another way to handle it more efficient, getting rid of the flag variable?

like image 353
Alex Avatar asked Dec 11 '22 21:12

Alex


1 Answers

You should never use except: because that catches ALL exceptions, including SystemExit, you should probably do:

try:
    if not check():
        raise MyNewException()
except ExceptionRaisedByCheck:
    raise MyNewException()

If the exception coming from check() is the same as the one you want to raise, you should change that.

Edit: If the exception is the same, you can also simply do this (Mark Byers had this in his answer, but it's gone now):

if not check():
    raise TheSameException()

This will propagate the exception or raise if False.

like image 163
Sebastian Blask Avatar answered Dec 30 '22 09:12

Sebastian Blask