Break the try and go directly to the exception if condition is false

Question:

I have a complex code in python with condition inside try:

try:
   if condition is True: execute the code 
   else: go to exception and don't execute the code
except:
   execute the except statement

I want to exit the try statement if condition is met

Asked By: Ravanelli

||

Answers:

Just manually raise an exception:

try:
    if condition:
        your code
    else:
        raise Exception('Exception message')
except:
    # except code here
Answered By: Murgalha
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.