Python: Getting Syntax Error while using Argument of an Exception [duplicate] - python

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

Related

How to print the exception string in <class> for Python [duplicate]

This question already has answers here:
Get fully qualified class name of an object in Python
(13 answers)
Closed 2 years ago.
I'm using Python 3.8.3 on Windows 10. I have the following code:
import # all the necessary modules
try:
# do something
except WebDriverException:
print(sys.exc_info()[0])
Upon the exception, I receive the following:
<class 'selenium.common.exceptions.SessionNotCreatedException'>
How do I get print() to output only the string within <class>?:
selenium.common.exceptions.SessionNotCreatedException
Any help would be appreciated.
To get the full path of an exception, use the inspect.getmodule method to get the package name and use type(..).__name __ to get the class name.
except WebDriverException as ex:
print (type(ex).__name__)
For the full name, try
import inspect
.....
print(inspect.getmodule(ex).__name__, type(ex).__name__, sep='.')
To keep it simple, you can just parse the string you already have
print(str(sys.exc_info()[0])[8:-2]) # selenium.common.exceptions.SessionNotCreatedException
Maybe you can try this
import # anything
try:
# something
except Exception as e:
print(e)

try except not catching the exception [duplicate]

This question already has answers here:
Failed to catch syntax error python [duplicate]
(2 answers)
Closed 4 years ago.
I was taught that an empty except catches all kinds of exceptions, but when I try this block of code it doesn't catch the exception and raise a SyntaxError. What am I doing wrong?
try:
print "Hello"
except:
print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
even when I specify the kind of exception as SyntaxErrorit still doesn't catch it.
try:
print "Hello"
except SyntaxError:
print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
No. An empty except catches all types of runtime errors; a syntax error is not a runtime error by definition, because the code can't run at all.

Re-raising exception, in a way agnostic to Python 2 and Python 3 [duplicate]

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)

How to create an error message in Python? [duplicate]

This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 6 years ago.
I want to create an error message in Python, i.e. the program should be interrupted and an (if possible coloured) error message should be printed. For instance:
If a == 0:
Error("a should be nonzero")
In Matlab, you can do this using the error instruction. How can you do this in Python? I have found this page but I am not sure that is what I am looking for.
You can raise it like so:
if a == 0:
raise ValueError("a should be nonzero")
or simply by using assert as:
assert a!=0, "a should be nonzero!"

SyntaxError not excepting in Python 3 [duplicate]

This question already has answers here:
Can Syntax Errors be handled?
(2 answers)
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
I'm trying to write a block of code at the top of my programs that, if the program is accidentally run in Python 2.x, it will give an error message and quit, but if run in Python 3.x will run normally:
try:
print "Error: This program should only be run in Python 3."
raw_input('>')
exit()
except SyntaxError:
pass
print("I see you're running Python 3.")
# rest of program
This works correctly in Python 2.7 (i.e., it displays the error and quits), but when I run it in Python 3.3, I get a SyntaxError, even though I told it to have an exception.
File "version.py", line 2
print "This program should only be run in Python 3"
^
SyntaxError: invalid syntax
What am I missing?
SyntaxErrors are thrown at compile-time. You cannot catch them like runtime exceptions.
If you want to check python version, look at sys.version_info.
i.e.
import sys
if sys.version_info.major < 3:
sys.exit('This program should only be run in Python 3')
Here's a small example on how to do what you want:
import sys
if sys.version_info.major == 2:
print("Error: This program should only be run in Python 3.")
raw_input('>')
exit(0)
This code will run in python2 and python3. You don't need to use a try catch in that case. Since in python2, it happens that the ( and ) will have no effect since they aren't tuples. You can write that kind of thing and it will work in python2 and python3 without SyntaxError.

Categories

Resources