A colleague of mine mistakenly typed this (simplified) code, and was wondering why his exception wasn't getting caught:
>>> try:
... raise ValueError
... except IndexError or ValueError:
... print 'Caught!'
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError
Now I know that the correct syntax to catch both types of exception should be except (IndexError, ValueError):
, but why is the above considered valid syntax? And how does it work?
For example, the above code will throw a ValueError
and it won't get caught. But take this code:
>>> try:
... raise IndexError
... except IndexError or ValueError:
... print 'Caught!'
...
Caught!
The IndexError
will get caught. How is the or
evaluated, and what is it evaluated to?!
Thanks for any light you can shed!
try { // Code that might throw an exception throw new Exception('Invalid URL. '); } catch (FirstExceptionClass $exception) { // Code that handles this exception } catch (SecondExceptionClass $exception) { // Code that handles a different exception } finally { // Perform cleanup, whether an exception occurred or not. }
The syntax for the assert clause is − Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can use the try-except clause to catch and handle AssertionError exceptions, but if they aren't, the program will stop, and the Python interpreter will generate a traceback.
Example: Exception handling using try... In the example, we are trying to divide a number by 0 . Here, this code generates an exception. To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.
An event that occurs during the execution of a program that disrupts the normal flow of instructions is called an exception. Example: public static void Main ()
That's because IndexError or ValueError
is evaluated to IndexError
.
>>> IndexError or ValueError
<type 'exceptions.IndexError'>
The or
operator returns the first expression that evaluates to True
(In this case IndexError
), or the last expression, if none of them are True
.
So, your except statement is actually equivalent to:
except IndexError:
The result of the Boolean operations or
and and
is always one of the operands, so foo or bar
will evaluate to foo
if foo
is truthy, or bar
if foo
if falsy.
In this case both IndexError
and ValueError
are truthy so IndexError or ValueError
evaluates to IndexError
, and your except statement is equivalent to except IndexError
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With