Compile Python Error [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a Code from Python 2.4 and Want to Compile this code on Python 2.6 but I see this Error:
>>> py_compile.compile("Model.py")
SyntaxError: ('invalid syntax', ('pcbModel.py', 73, 19, ' msg = "%s: %s. The error occurred generating \'%s\'." % (sys.exc_type, sys.exc_value, bName)\n'))
and code is:
try:
pcb.Create(self.skipMeshing, analysisType = self.analysisType)
msg = "%s: %s. The error occurred generating '%s'." % (sys.exc_type, sys.exc_value, bName)
raise Exception, msg
continue
self.deactivate(bName)
how solve it?

It looks like you have a try clause, with no corresponding except. also, raise type, args form is deprecated, use raise type(args). also, sys.exc_type and friends are not thread safe. The syntactically correct version is:
# DON'T DO THIS, SEE BELOW
try:
pcb.Create(self.skipMeshing, analysisType = self.analysisType)
except Exception as e:
msg = "%s: %s. The error occurred generating '%s'." % (type(e), e, bName)
raise Exception(msg)
However, It appears as though you are trying to "catch" the exception, compute some sort of error message and raise an exception. exceptions already do that. the idomatic version of the above is actually,
pcb.Create(self.skipMeshing, analysisType = self.analysisType)
with no try, no except and no raise. If pcb.Create() raises an exception, it has already raised an exception, you don't need to raise another one.

Related

How to print out the line of where the exception is coming from [duplicate]

This question already has answers here:
When I catch an exception, how do I get the type, file, and line number?
(7 answers)
Closed 1 year ago.
def println(text: str):
try:
print(text)
if not type(text) == str:
raise TypeError(f"argument \"text\" should be type \"str\". not type \"{type(text)}\"".)
except TypeError as err:
print(err)
This works fine and it says:
argument "text" should be type "str". not type "<class 'int'>".
but I don't see what line it's coming from. It's coming from line 4 and it doesn't say the line where the error is coming from. This makes it hard and frustrating to debug errors.
import traceback
traceback.print_exc()
will use the same default traceback formatting the interpreter uses for uncaught exceptions.
Or, better yet, don't catch the exception at all and let it be handled elsewhere? If you do need to wrap an exception to change its type or message, you can do
except SomeException as exc:
raise RuntimeError("a thing broke") from exc
which will retain the original exception and traceback.

How to raise additional error in Python and keep cause in stack trace?

I wrote
try:
...
except Exception as e:
raise ValueError(e, "Was unable to extract date from filename '%s'" % filename)
and now, when exception occurs inside try block, I loose information about it. I stack trace printed I see only line number with raise statement and no infomation about where actual e occured.
How to fix?
Use raise exc from another_exc:
try:
...
except Exception as e:
raise ValueError("Was unable to extract date from filename '%s'" % filename) from e
Adding the from e will make sure there's two tracebacks connected by The above exception was the direct cause of the following exception".

Exception message best practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've written a small production-level Flask application in Python with standard exception handling. Most of the time I'm just logging the exception message and it looks like this
try:
#Do something
except Exception, e:
logger.error('Exception in LoadValidationDocs in main.py : %s' % str(e.args))
return None
I was wondering if I should keep all such error messages in a separate strings.py file like
standard_exception_message = 'Exception in %s in %s, Exception Args : %s'
and get function and module name at run time like
import inspect
function_name = inspect.stack()[0][3]
file_name = os.path.basename(__file__)
logger.error(strings. standard_exception_message % (function_name, file_name, str(e.args)))
I just want to know whether it's necessary to do that and is it even the correct way of doing it considering my current scenario.
You can use logging.exception instead of logging.error. It will take care of looking for the function, module name etc. for you in a formatted way:
import logging
try:
# Do something that will fail
x = 1 / 0
except Exception as e:
logging.exception("This is my message when an error happens here.")
It gives:
ERROR:root:This is my message when an error happens here.
Traceback (most recent call last):
File "question39724934.py", line 5, in compute
x = 1 / 0
ZeroDivisionError: division by zero

Catching an exception in clone_saved_path()

I'm trying to figure out how to get the exception to show for this function
clone_saved_path():
def clone_saved_path():
except OSError as e:
# If the error was caused because the source wasn't a directory
print('Directory not copied. Error: %s' % e)
print("got here. [4]")
except:
print("Another error occurred in clone_saved_path() ")
print("got here. [5]")
When I run my code, it hits the last except block and outputs:
print("Another error occurred in clone_saved_path() ")
I know this may sound basic, but I need to figure out how to show the actual exception.
https://docs.python.org/3/library/sys.html#sys.exc_info
"This function returns a tuple of three values that give information about the exception that is currently being handled."
So you could do something like the below (suggested here: https://docs.python.org/3/tutorial/errors.html#handling-exceptions):
import sys
# ...
except:
print("Another error occurred in clone_saved_path() ")
print(sys.exc_info()[0]) # type of exception
raise

proper way to get nice string from exception

I want to generate a one-line string from an Exception which tells me what happened where (don't need a full backtrace). The following information would be nice:
filename / linenumber
exception type
exception description (what you get from str(e))
nice to have: function/method/class
Currently I do the following:
import os
...
try:
os.nonexisting()
except Exception as e:
t = e.__traceback__
tbf = e.__traceback__.tb_frame
print('%s:%d: %s in %s(): "%s" ' %
os.path.basename(tbf.f_code.co_filename),
t.tb_lineno,
e.__class__.__name__,
tbf.f_code.co_name, e))
which gives me:
foo.py:203: AttributeError in foo(): "'module' object has no attribute 'nonexisting'"
Is there a more elegant way to print out the details given in this example? I'm thinking about s.th. like
print(e.format('%f: %l: %t %F: "%w"'))
I'd like to avoid importing extra modules except there is one exactly for this purpose.
I think traceback.format_exception_only does exactly what you want.
try:
os.nonexisting()
except Exception as e:
print(traceback.format_exception_only(e.__class__, e))

Categories

Resources