Why isn't my code excepting the errors? - python

I have this little piece of code I wrote that isn't excepting the errors that could be thrown at it. Here's the code:
def println(stringint):
try:
print stringint
except (SyntaxError, NameError):
print "Invalid format."
I run the code from the python interpreter like this, and only like this:
>>> import pcl
>>> pcl.println("Hello")
Why aren't the errors being excepted? How can I catch the errors?

Those errors that has to do with syntax are parse level errors, which means, that are errors that take place before that particular code being interpreted.
The following arenĀ“t the same type of errors:
print("Hello) # Note the missing '"'
that
print(4/0) # Syntactically correct, but obviously an error.
Hence, syntax error can't be handled by the try -- except block.
See this answer for more detail: SyntaxError inconsistency in Python?

Your code works fine, "Hello" should raise neither an EOLError nor a NameError, because the quotes are closed, and it is a string.

Related

Is there a simple way to comment out or diable a python try statement without re-indenting

Problem:
Sometimes it is nice to be able to remove or apply a try statement temporarily. Is there a convenient way to disable the try statement without re-indenting?
For example, if there was a python block statement equivalent called "goForIt:" one could edit the word "try:" to "goForIt:" and it would just execute the block as though it were not wrapped in a "try" and ignore the "except" line too.
The problem I'm trying to solve is that while I want the try statement in production I want to be able to remove it temporarily while debugging to see the error traceback rather than have it trap and process the exception.
Currently I work around this by commenting out the "try" then re-indent the code in the block. Then comment out the entire "except" block. This seems clumsy.
Instead of removing the try, you could make the except re-raise the exception:
try:
raise ValueError('whoops')
except ValueError as e:
raise # <-- just put this here
print('caught')
This will raise the error, just as if it were not caught:
ValueError Traceback (most recent call last)
<ipython-input-146-a6be6779c161> in <module>
1 try:
----> 2 raise ValueError('whoops')
3 except ValueError as e:
4 raise
5 print('caught')
ValueError: whoops
I do not believe there is a way to fix this.
Is it adequate to catch the exception, print it out and, if wanted, end the program?
try:
# code
except Exception as e:
print(e)
# end program if wanted
If you want a none code solution you need to use an IDE or a good text editor.
I am using Visual Studio code where I can indent with a keyboard shortcut (Ctrl + ` in my case)
(This is not my answer, but the answer from Alani's comment. If credits, find the original comment under the question.)
The solution is good because it allows global replacement:
try: --> if 1: # try:
except --> if 0: # except
The 2nd one is a little unsure. Exact and full word match should be used, or replace twice (for except<space> and except:). Or you can fix error fast by hand if there is any.
The replacement back is sure.
I need now such solution to debug error in strawberry which is only printed. So I think I need deactivate all try/except structures in 3 libraries (strawberry + 2 libs for django).

Can Syntax Errors be handled?

Consider the following code:
try:
if True a = 1 #It's missing a colon So it's a SyntaxError!!!!!!!
except SyntaxError:
print 'hey'
You'd expect it to print hey However It raises a SyntaxError, The same error I'm trying to avoid. So Can all Exceptions be handled using a try-except block? Well If SyntaxError's were an exception why is it included in the built-in exceptions? and finally how can I fix the above piece of code so that it handles the exception properly?
Note: I know what I'm trying to do Is utterly pointless and serves no real purpose
SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it's (usually) thrown are a bit unusual.
A syntax error means that the code featuring said error cannot be parsed. It doesn't even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can't be caught from within the program.
More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can't catch its own syntax errors.
The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of "invoking the parser" include:
compile, exec, eval
import statements
Several functions in modules like ast, tokenizer, parser, etc.
Of course you need SyntaxError as a built-in exception - what else should be raised if the compiler/parser encounters a syntax error?
You're right that this error usually happens at compile time, which is before you're able to catch it (runtime). (And how would you recover from it?)
I can think of one exception, though:
>>> try:
... eval("hello =")
... except SyntaxError:
... print("Hey! Who's using eval() anyway??")
...
Hey! Who's using eval() anyway??

Any way to save a traceback object in Python

I was looking to possibly try and save a traceback object and somehow pickle it to a file that I can access. An example of a use case for this is if I am submitting some python code to a farm computer to run and it fails, it would be nice to be able to open a session and access that traceback to debug the problem rather than just seeing a log of the traceback. I do not know if there is any sort of way to do this but thought it would be worth asking why it couldn't if so.
okay so you can use traceback.print_exception(type, value, traceback[, limit[, file]]) and save it in a text or json or you can refer to docs
if you find it helpful please mark it correct or upvote thanx..:)
Depending on how you've written your code, the try statement is probably your best answer. Since any error is just a class that inherits Python's builtin Exception, you can raise custom errors everywhere you need more information about a thrown error. You just need to rename your errors or pass in an appropriate string as the first argument. If you then try your code and use the except statement except CustomError as e, you can pull all the information you want out of e in the except statement as a regular instance. Example:
Your code would be:
def script():
try: codeblock
except Exception as e: raise Error1('You hit %s error in the first block'% e)
try: codeblock 2
except Exception as e: raise Error2('You hit %s error in the second block' % e)
try: script()
except Exception as e:
with open('path\to\file.txt','w') as outFile:
outFile.write(e)
The last part is really nothing more than creating your own log file, but you have to write it down somewhere, right?
As for using the traceback module mentioned above, you can get error information out of that. Any of the commands here can get you a list of tracebacks:
http://docs.python.org/2/library/traceback.html
On the otherhand, if you're trying to avoid looking at log files, the traceback module is only going to give you the same thing a log file would, in a different format. Adding your own error statements in your code gives you more information than a cryptic ValueError about what actually happened. If you print the traceback to your special error, it might give you still more information on your issue.

Failed to write to file but generates no Error

I'm trying to write to a file but it's not working. I've gone through step-by-step with the debugger (it goes to the write command but when I open the file it's empty).
My question is either: "How do I see what the error is so I can debug?", "What can go wrong when trying to write to a file that would cause it to behave this way?".
sqlScript = open('script-file.sql', 'a')
try:
sqlScript.write(sqlLine)
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
This should be simple but I can't seem to find an answer. Also, I apologize in advance as English is a second language.
Edit: I put a print statement just before and the string is not empty.
Edit2: I'm using python 2.6 if that factors in somehow.
Edit 3: I've found a "solution" to my error. I decided to try and run my script using IDLE instead of PyCharm and it works like a charm (pun intended). I have no clue why, but there it is. Any reason why that would happen?!
Building on Chris Morris' answer, maybe do something like this:
try:
sqlScript.write(sqlLine)
except Exception as e:
print type(e)
print str(e)
This will catch any Exception thrown (provided it's a subclass of Exception, of course) and tell you the type and the error message.
Also, it's possible to define multiple except: cases for different possible exceptions, so maybe try doing that for each exception that might be potentially thrown/raised.
The following code allows you to see what exception it is that is being thrown, and see a trace of where it originated from.
try:
sqlScript.write(sqlLine)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
See http://docs.python.org/tutorial/errors.html for more info.
You have to put your cursor at the beginning of the file. You can do that with seek method:
myScript.seek(0)
See this answer: https://stackoverflow.com/a/2949648/2119117
If no exception is being tossed, I'd suspect the string variable 'sqlLine' is empty.
Did you print it before the write statement?
Are the keywords in the script in lowercase? The same thing happened to me in another db and I solved it by changing words to UPPERCASE.
Your current working directory isn't what you expect it to be and it's successfully writing to some script-file.sql in another directory. Try printing os.getcwd() and make sure it's what you expect, and look in that directory.
It happened on my linux environment but work on windows try
sqlScript = open('script-file.sql', 'a', buffering=False)
or
sqlScript = open('script-file.sql', 'a', 0)

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.

Categories

Resources