I write my code in Python 3.8.9 with this line, which works:
try:
...
except Exception as e:
if "AlreadyExistsException" in e:
When deploying it in a Python 3.6 environment, I get this error:
TypeError: argument of type 'AlreadyExistsException' is not iterable
Could someone help confirming that the operation to check for the existence of a substring AlreadyExistsException in the error string e like above does not work in Python 3.6? I don't have Python 3.6 to test this out and too hesitated to install it to test this error. And if this is true, what is a workable way to check for substring in Python 3.6?
The correct way to check for a specific type of Exception would be:
try:
...
except AlreadyExistsException as e:
# do something in response to this specific exception
...
except (SomeOtherException, AndAnotherException) as e:
# do something in response to those specific exceptions
...
Related
I am trying to understand this code and the use of the following pattern:
try:
...
except Exception:
raise
What is the point of re-raising the exception like this? Don't you get the same result if you remove the whole try-except block?
Yes, that code achieves nothing.
I've been playing around with this but I can't quite seem to figure out the syntax. I'm trying to exception handle a specific exception thrown from an Amazon API lib.
It throws the exception:
class 'amazon.api.AsinNotFound'
I've tried:
except AsinNotFound
and
except amazon.api.AsinNotFound
I can handle it with just an except but I want to be able to catch this specific case if possible. If it's not I could look for the text in sys.exc_info() but that doesn't seem like a neat way of doing it.
Example:
try:
DoSomethingWithASIN
except amazon.api.AsinNotFound:
print "No ASIN"
except:
print "this part triggers instead"
Is there anyway to write an exception catch code that's compatible from python 2.4 to python 3?
Like this code:
# only works in python 2.4 to 2.7
try:
pass
except Exception,e:
print(e)
# only works in python 2.6 to 3.3
try:
pass
except Exception as e:
print(e)
Trying to write code that works in both Python 2 and Python 3 is ultimately rather futile, because of the sheer number of differences between them. Indeed, a lot of projects are now maintained in separate Python 2 and Python 3 versions as a result.
That said, if you're hell-bent on doing this in a super-portable way...
import sys
try:
...
except Exception:
t, e = sys.exc_info()[:2]
print(e)
What is the difference between ',' and 'as' in except statements, eg:
try:
pass
except Exception, exception:
pass
and:
try:
pass
except Exception as exception:
pass
Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.
If they are both valid in 2.6 which should I use?
The definitive document is PEP-3110: Catching Exceptions
Summary:
In Python 3.x, using as is required to assign an exception to a variable.
In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
In Python 2.5 and earlier, use the comma version, since as isn't supported.
Yes it's legal. I'm running Python 2.6
try:
[] + 3
except Exception as x:
print "woo hoo"
>>>
woo hoo
Update: There is another reason to use the as syntax. Using , makes things a lot more ambiguous, as others have pointed out; and here's what makes the difference. As of Python 2.6, there is multicatch which allows you to catch multiple exceptions in one except block. In such a situation, it's more expressive and pythonic to say
except (exception1, exception2) as e
rather than to say
except (exception1, exception2), e
which would still work
the "as" syntax is the preferred one going forward, however if your code needs to work with older Python versions (2.6 is the first to support the new one) then you'll need to use the comma syntax.
If you want to support all python versions you can use the sys.exc_info() function like this:
try:
a = 1/'0'
except (ZeroDivisionError, TypeError):
e = sys.exc_info()[1]
print(e.args[0])
(source:http://python3porting.com/noconv.html)
As of Python 3.7 (not sure about other versions) the 'comma' syntax is not supported any more:
Source file exception_comma.py:
try:
result = 1/0
except Exception, e:
print("An error occurred")
exit(1)
exit(0)
$ python --version --> Python 2.7.10
$ python exception_comma.py
An error occurred
$ python3 --version --> Python 3.7.2
$ python3 exception_comma.py
File "exception_comma.py", line 3
except Exception, e:
^
SyntaxError: invalid syntax
I wrote a method that does some stuff and catches bad filenames. what should happen is if the path doesn't exist, it throws an IOError. however, it thinks my exception handling is bad syntax... why??
def whatever():
try:
# do stuff
# and more stuff
except IOError:
# do this
pass
whatever()
but before it even gets to calling whatever(), it prints the following:
Traceback (most recent call last):
File "", line 1, in
File "getquizzed.py", line 55
except IOError:
^
SyntaxError: invalid syntax
when imported...help?!
Check your indenting. This unhelpful SyntaxError error has fooled me before. :)
From the deleted question:
I'd expect this to be a duplicate, but I couldn't find it.
Here's Python code, expected outcome of which should be obvious:
x = {1: False, 2: True} # no 3
for v in [1,2,3]:
try:
print x[v]
except Exception, e:
print e
continue
I get the following exception: SyntaxError: 'continue' not properly in loop.
I'd like to know how to avoid this error, which doesn't seem to be
explained by the continue documentation.
I'm using Python 2.5.4 and 2.6.1 on Mac OS X, in Django.
Thank you for reading
there's 1 more possible if you're privileged to have an older installation
and
you're using the 'as' syntax:
except IOError as ioe:
and
the parser's getting tripped up on 'as'.
Using as is the preferred syntax in Python 2.6 and better.
It's a syntax error in Python 2.5 and older. For pre-2.6, use this:
except IOError, ioe:
Just missing something in your try block, i.e. pass or anything, otherwise it gives an indentation error.
You will get a syntax error if you don't put something in side the try block.
You can put pass just to hold the space:
try:
# do stuff
# and more stuff
pass
except IOError:
# do this
pass