try except not catching the exception [duplicate] - python

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.

Related

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)

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

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

Failed to catch syntax error python [duplicate]

This question already has answers here:
SyntaxError inconsistency in Python?
(2 answers)
Closed 5 years ago.
try:
x===x
except SyntaxError:
print "You cannot do that"
outputs
x===x
^
SyntaxError: invalid syntax
this does not catch it either
try:
x===x
except:
print "You cannot do that"
Other errors like NameError, ValueError, are catchable.
Thoughts?
System specs:
import sys
print(sys.version)
->
2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
You can only catch SyntaxError if it's thrown out of an eval, exec, or import operation.
>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that
This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try statement is executed. If you use eval or its friends to cause more code to be parsed during the execution of the program, though, then you can catch it.
I'm pretty sure this is in the official manual somewhere, but I can't find it right now.
SyntaxErrors get raised when the file/code is parsed, not when that line of code is executed. The reason for this is simple -- If the syntax is wrong at a single point in the code, the parser can't continue so all code after that line is un-parseable.
In other words, you can only catch syntax errors when python is trying to parse something. This includes exec, eval, import:
>>> try:
... import junk
... except SyntaxError:
... print "Woo"
...
Woo
and various things regarding ast and the like.
Note that the python tutorial even distinguishes between SyntaxError and other exceptions although the distinction isn't as clear as the tutorial makes it seem (since you can in fact catch SyntaxError if you know when they get raised).

How to catch IndentationError [duplicate]

This question already has answers here:
SyntaxError inconsistency in Python?
(2 answers)
Closed 5 years ago.
First of all - I don't have a problem with bad-indentated code and I have an idea of how does this exception works like.
I ask, if there is any way to catch IndentationError in code with a try/except block? For example, let's say I'm writing a test for a function written by someone else. I want to run it in try/except block and handle all warning he/she could make. I know, that it's not a best example, but the first one coming to my mind. Please, don't focus on an example, but rather on problem.
Let's look at the code:
try:
f()
except IndentationError:
print "Error"
print "Finished"
The function:
def f():
print "External function"
And the result is:
External function
Finished
And that's something, I'm ready to understand, becouse indentation in external function was consistant.
But when the function look like that:
def f():
print "External function"
print "with bad indentation"
The exception is unhandled:
print "with bad indentation"
^
IndentationError: unexpected indent
Is there any way to achieve it? I guess that's the matter of compiling, and as far I don't see any possibility to catch. Does the except IndentationError make any sense?
Yes, this can be done. However, the function under test would have to live in a different module:
# test1.py
try:
import test2
except IndentationError as ex:
print ex
# test2.py
def f():
pass
pass # error
When run, this correctly catches the exception. It is worth nothing that the checking is done on the entire module at once; I am not sure if there's a way to make it more fine-grained.
IndentationError is raised when the module is compiled. You can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except, because with the IndentationError, Python won't be able to finish compiling the module, and no code in the module will be run.
You could use a tool such as pylint, which will analyse your module and report bad indentation, as well as many other errors.

catching an IOError in python

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

Categories

Resources