Does Python Command Exist Similar to (Catch and Throw) Ruby?

Asked

Viewed 92 times

-1

Exists in Python Similar to Ruby (Catch and Throw)? I’d like to jump like this:

a = 10
throw :pularparaaqui if a == 10

catch :pularparaaqui do
end

2 answers

2


Similar to the "catch" and "throw" of various languages, in Python we have the the "Try"/"except" blocks and the "raise" command However the use you are making in your example is basically that of the "goto" command, which exists in C, in Basic, and is universally recognized as a bad programming practice. Why the use of GOTO is considered bad?

This use, as you describe it, is not allowed in Python.
The flow control mechanism allows, if you raise an exception with the "raise" command, the processing jumps to the next "except" block that specifies that exception - only that this only happens if the exception occurs within a "Try block".
The block does not need to be visible in the same scope as you are writing - it may be in the code that calls the function where the "raise" is (or even multiple layers 'above') - but the except block has to be in the same scope as the "Try" block".

Yet another detail is that in general we specialize the Exceptions, creating subclasses of "Exception" - but this is not strictly necessary.

class MinhaExcecao(Exception): pass

try:
     if a == 10:
         raise MinhaExcecao
     ...
except MinhaExcecao:
    # código continua aqui.

0

In Python there are reserved words try, raise and except which are used exclusively for the treatment of exceções.

In the case exemplified in your question, there is no need for an exception control to "skip" the flow, you can simply use a block if/else equivalent, look at that:

if( a == 10 ):
   print("a == 10");
else:
   print("a != 10");

Or:

if( a != 10 ):
   print("a != 10");
else:
   print("a == 10");
  • Nothing to do. I want something like the drop.

  • @thegrapevine: I’m sorry, I don’t like Spaghetti, is a matter of taste.

  • Your question has been widely discussed here and here, maybe light your way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.