This question already has answers here:
Python: Catching specific exception
(3 answers)
Closed 6 years ago.
I am trying to pass a specific key error.by this two.
try:
per_visit_large_store = 100 * dic_data[mac]['Retail Store']['No. of visit to large store']/float(dic_data[mac]['Total no. of walk_in'])
except KeyError: 'Retail Store'
pass
and
try:
per_visit_large_store = 100 * dic_data[mac]['Retail Store']['No. of visit to large store']/float(dic_data[mac]['Total no. of walk_in'])
except KeyError: 'Retail Store':
pass
both of this raises Indentation and syntax error respectively. What exactly I am doing wrong? I am using python 2.7
Syntax is incorrect, it should be:
try:
# some code there
except KeyError as e:
caused_key = e.args[0]
if caused_key == 'Retail Store':
pass
See more in Python Exception tutorial
Good Luck :)!
The correct syntax is:
try:
...
except KeyError:
pass
If you want to catch a specific key then you need to check the message of the error:
d = {'a':1, 'b':2}
try:
d['c']
except KeyError as e:
if e.message == 'c':
blah
else:
raise KeyError, e
This will only continue the code if the key is 'c'. If it is not, then the error is raised.
Related
This question already has answers here:
python sys.exit not working in try [duplicate]
(2 answers)
Closed 4 years ago.
I have a small python script which I have written specifically for this question.
#!/usr/bin/python3
import sys
def testfunc(test):
if test == 1:
print("test is 1")
else:
print("test is not 1")
sys.exit(0)
try:
testfunc(2)
except:
print("something went wrong")
print("if test is not 1 it should not print this")
What I was expecting is that when test = 2 the script should exit. Instead what I get is this;
test is not 1
something went wrong
if test is not 1 it should not print this
I am new to python but not to scripting/coding. I have searched all over the place and every answer is simply "use sys.exit()"
Well it seems that sys.exit() has what seems to be unexpected behaviour when it is contained within try/except. If I remove the try it behaves as expected
Is this normal behaviour? If so is there a way to hard exit the script with out it continuing to execute into the exception block when test = 2?
Note: this is sample code that is a simplified version of the logic I am intending to use in another script. The reason the try/except is there is because testfunc() will be called using a variable and I want to catch the exception if an invalid function name is provided
Thanks in advance
Edit: I have also tried quit(), exit(), os._exit() and raise SystemExit
Here, sys.exit(0) raises a SystemExit exception.
Since you put the calling code inside a Try-Except block, it's as expected caught. If you want to propagate the exception, recall a sys.exit() with the code status:
try:
testfunc(2)
except SystemExit as exc:
sys.exit(exc.code) # reperform an exit with the status code
except:
print("something went wrong")
print("if test is not 1 it should not print this")
I am trying to debug python code, I want to pin point the line number in which error occurs. As per the posts found asked here the code gives the line no of the function being called. eg
if __name__ == '__main__':
try:
foo()
except:
<the code to print line no when error occurs>
But it gives me the line no of foo(),
Please help to find the exact line no in which error occurs.
Thanks,
You have to use the third return value of sys.exc_info() they call exc_tb in your example. Instead of using exc_tb.tb_lineno, you can browse the traceback object using traceback.extract_tb(exc_tb). The repr look like :
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
I suppose the line you are looking for is the last line of the structure. I haven't tested but this should do :
import sys, os, traceback
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
tb = traceback.extract_tb(exc_tb)[-1]
print(exc_type, tb[2], tb[1])
I was reading a similar question Returning error string from a function in python. While I experimenting to create something similar in an Object Oriented programming so I could learn a few more things I got lost.
I am using Python 2.7 and I am a beginner on Object Oriented programming.
I can not figure out how to make it work.
Sample code checkArgumentInput.py:
#!/usr/bin/python
__author__ = 'author'
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class ArgumentValidationError(Error):
pass
def __init__(self, arguments):
self.arguments = arguments
def print_method(self, input_arguments):
if len(input_arguments) != 3:
raise ArgumentValidationError("Error on argument input!")
else:
self.arguments = input_arguments
return self.arguments
And on the main.py script:
#!/usr/bin/python
import checkArgumentInput
__author__ = 'author'
argsValidation = checkArgumentInput.ArgumentValidationError(sys.argv)
if __name__ == '__main__':
try:
result = argsValidation.validate_argument_input(sys.argv)
print result
except checkArgumentInput.ArgumentValidationError as exception:
# handle exception here and get error message
print exception.message
When I am executing the main.py script it produces two blank lines. Even if I do not provide any arguments as input or even if I do provide argument(s) input.
So my question is how to make it work?
I know that there is a module that can do that work for me, by checking argument input argparse but I want to implement something that I could use in other cases also (try, except).
Thank you in advance for the time and effort reading and replying to my question.
OK. So, usually the function sys.argv[] is called with brackets in the end of it, and with a number between the brackets, like: sys.argv[1]. This function will read your command line input. Exp.: sys.argv[0] is the name of the file.
main.py 42
In this case main.py is sys.argv[0] and 42 is sys.argv[1].
You need to identifi the string you're gonna take from the command line.
I think that this is the problem.
For more info: https://docs.python.org/2/library/sys.html
I made some research and I found this useful question/ answer that helped me out to understand my error: Manually raising (throwing) an exception in Python
I am posting the correct functional code under, just in case that someone will benefit in future.
Sample code checkArgumentInput.py:
#!/usr/bin/python
__author__ = 'author'
class ArgumentLookupError(LookupError):
pass
def __init__(self, *args): # *args because I do not know the number of args (input from terminal)
self.output = None
self.argument_list = args
def validate_argument_input(self, argument_input_list):
if len(argument_input_list) != 3:
raise ValueError('Error on argument input!')
else:
self.output = "Success"
return self.output
The second part main.py:
#!/usr/bin/python
import sys
import checkArgumentInput
__author__ = 'author'
argsValidation = checkArgumentInput.ArgumentLookupError(sys.argv)
if __name__ == '__main__':
try:
result = argsValidation.validate_argument_input(sys.argv)
print result
except ValueError as exception:
# handle exception here and get error message
print exception.message
The following code prints: Error on argument input! as expected, because I violating the condition.
Any way thank you all for your time and effort, hope this answer will help someone else in future.
I am reading python tutorial here and there is one thing that I can't quite make sense out of. From the docs:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
From the explanation in the doc:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
My question is it how does it protect against accidentally catching an exception that wasn't raised in this try block. I don't see what they mean. Can anyone give an example?
One possible alternative approach that you might try is this:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
print arg, 'has', len(f.readlines()), 'lines'
f.close()
except IOError:
print 'cannot open', arg
Here if there is an exception during f.readlines() or f.close() then it will be caught by the except block and you will get the error message 'cannot open' which is wrong.
I'm trying to make a generic error handler, something like "when others" in Oracle. The examples that I can find all involve catching a specific expected error.
Try:
some_function()
Except: #I don't know what error I'm getting
show_me_error(type_of_error_and_message)
This is very well-documented. But may be you just need Sentry?
try:
1/0
except Exception as e:
print('%s' % type(e))
>>>
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)
import traceback
try:
some_function()
except Exception as e:
message = traceback.format_exc()
print(message)
To print the exception using Python 3, you'll want to use type(e). Example below:
try:
1/0
except Exception as e:
print(type(e))
>>> <class 'ZeroDivisionError'>
And then you can catch the exception with:
try:
1/0
except ZeroDivisionError:
print('Cannot divide by 0')
except Exception as e:
print(type(e))
>>> Cannot divide by 0
To print an exception in Python 3:
try:
# your code
except Exception as e:
print(e)