Is there in Python Something Similar to (Catch and Throw) of Ruby? I would like to jump like this:
a = 10
throw :pularparaaqui if a == 10
catch :pularparaaqui do
end
Is there in Python Something Similar to (Catch and Throw) of Ruby? I would like to jump like this:
a = 10
throw :pularparaaqui if a == 10
catch :pularparaaqui do
end
Similar to "catch" and "throw" of various languages, in Python we have the the "try" / "except" blocks and the "raise" command - However the use you are doing 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 usage, as you describe, is not allowed in Python. The flow control mechanism allows you to raise an exception with the raise command, processing skips to the next except that specifies that exception - only this only happens if the exception occurs inside a "try" block. The block does not need to be visible in the same scope as the one you are writing in - it may be in the code that calls the function where the "raise" is (or even several layers 'up') - but the except block has to be in the same scope of the "try" block.
Yet another detail is that we generally specialize 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.
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 exception handling to "skip" the flow, you can simply use a block if/else
equivalent, see:
if( a == 10 ):
print("a == 10");
else:
print("a != 10");
Or:
if( a != 10 ):
print("a != 10");
else:
print("a == 10");