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
...
This question already has answers here:
Python exception chaining [duplicate]
(2 answers)
Closed 4 years ago.
I have a script in Python 3, which re-raises an exception using the 'from' keyword (as demonstrated in the answer to this Stackoverflow question: Re-raise exception with a different type and message, preserving existing information )
I have to go back now and make the script compatible with Python 2.7. The 'from' keyword can not be used this way in Python 2.7. I found that in Python 2, the way to re-raise an exception is as follows:
try:
foo()
except ZeroDivisionError as e:
import sys
raise MyCustomException, MyCustomException(e), sys.exc_info()[2]
However, while this syntax works in Python 2.7, it does not work for Python 3.
Is there an accepted way to re-raise exceptions in Python which work for both Python 2.7 and Python 3?
# Python 3 only
try:
frobnicate()
except KeyError as exc:
raise ValueError("Bad grape") from exc
# Python 2 and 3:
from future.utils import raise_from
try:
frobnicate()
except KeyError as exc:
raise_from(ValueError("Bad grape"), exc)
Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints <class 'Exception'>. I knew this used to work in python 2, but how do I do it in python3?
I'm guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:
def fails():
x = 1 / 0
try:
fails()
except Exception as ex:
print(ex)
To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.
In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately.
(This is discussed in detail in the Python 3 Language Reference: The try Statement.)
There are other compound statements that use as. The first is the with statement:
#contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with opening(filename) as f:
# ...read data from f...
Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use.
(This is discussed in detail in the Python 3 Language Reference: The with Statement.)
As of Python 3.10, match statements also use as:
from random import randint
match randint(0, 2):
case 0|1 as low:
print(f"{low} is a low number")
case _:
print("not a low number")
match statements take an expression (in this case, randint(0, 2)) and compare its value to each case branch one at a time until one of them succeeds, at which point it executes that branch's block. In a case branch, as can be used to assign the value of the branch to a variable if that branch succeeds. If it doesn't succeed, it is not bound.
(The match statement is covered by the tutorial and discussed in detail in the Python 3 Language Reference: match Statements.)
Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:
import foo.bar.baz as fbb
This is discussed in detail in the Python 3 Language Reference: The import Statement.
These are the changes since python 2:
try:
1 / 0
except Exception as e: # (as opposed to except Exception, e:)
# ^ that will just look for two classes, Exception and e
# for the repr
print(repr(e))
# for just the message, or str(e), since print calls str under the hood
print(e)
# the arguments that the exception has been called with.
# the first one is usually the message. (OSError is different, though)
print(e.args)
You can look into the standard library module traceback for fancier stuff.
Try
try:
print(undefined_var)
except Exception as e:
print(e)
this will print the representation given by e.__str__():
"name 'undefined_var' is not defined"
you can also use:
print(repr(e))
which will include the Exception class name:
"NameError("name 'undefined_var' is not defined",)"
Here is the way I like that prints out all of the error stack.
import logging
try:
1 / 0
except Exception as _e:
# any one of the follows:
# print(logging.traceback.format_exc())
logging.error(logging.traceback.format_exc())
The output looks as the follows:
ERROR:root:Traceback (most recent call last):
File "/PATH-TO-YOUR/filename.py", line 4, in <module>
1 / 0
ZeroDivisionError: division by zero
LOGGING_FORMAT :
LOGGING_FORMAT = '%(asctime)s\n File "%(pathname)s", line %(lineno)d\n %(levelname)s [%(message)s]'
Although if you want a code that is compatible with both python2 and python3 you can use this:
import logging
try:
1/0
except Exception as e:
if hasattr(e, 'message'):
logging.warning('python2')
logging.error(e.message)
else:
logging.warning('python3')
logging.error(e)
[In Python3]
Let's say you want to handle an IndexError and print the traceback, you can do the following:
from traceback import print_tb
empty_list = []
try:
x = empty_list[100]
except IndexError as index_error:
print_tb(index_error.__traceback__)
Note: You can use the format_tb function instead of print_tb to get the traceback as a string for logging purposes.
Hope this helps.
Don't use print(e), since that won't print a stack trace, which is a nightmare for debugging. traceback.print_exception is what you're looking for:
import traceback
try:
assert False
except Exception as e:
traceback.print_exception(e)
I've use this :
except (socket.timeout, KeyboardInterrupt) as e:
logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
break
Let me know if it does not work for you !!
You can do:
with self.assertRaisesMessage(ValueError, 'invalid literal for int()'):
int('a')
Reference
This question already has answers here:
In Python, what's the difference between 'except Exception as e' and 'except Exception, e' [duplicate]
(3 answers)
Closed 7 years ago.
I want to use Argument of an Exception to show additional information while an error occur in my code.
Here is my code.
ArgumentOfAnException.py
from pip._vendor.distlib.compat import raw_input
def to_celsius(f):
try:
c = (f-32)*5/9;
return c;
except ValueError, Argument:
print("The argumet doesn't contain number\n", Argument);
return;
f = raw_input("Enter temperature in *F : ");
print("Temperature in Celsius : ", to_celsius(float(f)));
print("Thank you...");
Here I use Argument variable to display additional information when error occur in my code but after running the program there will show a syntax error in the console output and the error is like
File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\Error\ArgumentOfAnException.py", line 7
except ValueError, Argument:
^
SyntaxError: invalid syntax
It seems like you're using python 3.x.
Use following syntax (using as):
except ValueError as Argument:
Reference: try statement - Python 3 documentation
This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 4 months ago.
I'm new to Python and struggling with handling self-defined errors. When my code spots the error, I want it to throw an error in red font and take me back to the Python terminal without killing Python.
I came across sys.exit() looking for an answer, but it quits Python completely. Do you know of an alternative that throws back an error in red font and takes me back to the terminal?
This is what I have so far.
import sys
def do_something(parameter):
if parameter > 100:
# quit the function and any function(s) that may have called it
sys.exit('Your parameter should not be greater than 100!')
else:
# otherwise, carry on with the rest of the code
Please let me know if I'm not clear and I'll be happy to provide more details. Thank you all in advance!
You have two options (at least).
Using a return statement:
def do_something(parameter):
if parameter > 100:
# display error message if necessary
return # 'exit' function and return to caller
# rest of the code
You can also return soemthing passing the something value back to the caller. This can be used to provide a status code for instance (e.g. 0: success, 1: error).
Or a better approach is to raise an exception:
def do_something(parameter):
if parameter > 100:
raise ValueError('Parameter should...')
# rest of the code
try:
do_something(101)
except ValueError, e:
# display error message if necessary e.g. print str(e)
See exceptions in the Python manual.
There are built-in exception classes (like ValueError above). You can also define your own as follows:
class ParameterError(Exception):
pass
You can also add additional code to your custom exception classes to process parameters, display custom error messages, etc...
The built-in exceptions are listed here.
Define a custom exception, and raise it.
class MyError(Exception):
pass
...
if parameter > 100:
# quit the function and any function(s) that may have called it
raise MyError('Your parameter should not be greater than 100!')
(although actually, now I think about it, you could just use a built-in exception: ValueError would seem appropriate).