I am using python unittest and trying to catch the exceptions. I have tried with self.fail but in that case, once there is an exception, it is a failure and it stops running the rest of the code
What can I try so even if one case fails, it still executes the rest of the cases ?
I am trying to avoid printing the exceeptions.
Code currently using:
if 'Anonymous' in elem_welcome.text:
pass
else:
self.fail('Test Failed: Logout Failed'))
Use the try and except block and name the said 'error' on the except block
E.g. Error is 'NameError'
try:
#cases
except NameError:
#other cases
You can read more here Handling Exceptions
You can make every test to be a function and call it from the main block. This way each one will get executed and the failed once will return the fail reason to be filed by main block.
Related
I am new to "Try & Except" so sorry if my question is very novice. I tried to search the reason but didn't find any.
I am trying a very simple Try an Except for read_csv:
try:
cntrl = pd.read_csv(my_directory + file, sep='|')
except FileNotFoundError:
logger.critical("file not found")
logger.info(f"file imported. Number of records: {len(cntrl )}")
So, when I don't have the file, the try and except just prints the error and moves to next line of "logger.info" code to give the below error.
UnboundLocalError: local variable 'cntrl' referenced before assignment
Shouldn't the code stop when error is found and not move to next? When I run the read_csv code without try and except, it stops and throws the error as FileNotFound.
You can add some code that should run only if what's in the try statement doesn't raise an except state with else:
https://docs.python.org/3/tutorial/errors.html
Besides that, if you want your code to stop if an error is raised, use sys.exit() inside the except statement:
https://docs.python.org/3/library/sys.html
How do I stop a program when an exception is raised in Python?
However, as Aryerez stated, usually the point of the try-except statement is to prevent the code from crashing. If you want it to stop running if an error happens, you can just remove the try-catch statements altogether.
I am using pathlib.Path.rglob to browse through some files in a directory hierarchy. However one of the (sub-sub-...) directory cannot be parsed and an exception is thrown.
import pathlib
for file in pathlib.Path(r'\\path\to\shared\folder').rglob('*.foo'):
pass
# OSError: [WinError 59] An unexpected network error occurred
Catching the exception in the body of the for loop makes no sense as the exeption occurs in rglob. Putting the entire loop within a try block does catch the exception, but then I cannot resume the computation.
Does anybody have a clue about how to do that with pathlib.Path.rglob? A work around is to use good old os.walk but I would be interested in knowing a solution for this supposedly more modern tool.
First of all, try to run filePaths = Path(r'\\path\to\shared\folder').rglob('*.foo') in your python shell to see whether it completes without an error. If so, you can try to catch runtime-exceptions (probably due to unstable network connection) during the iteration.
def try_loop(g):
while True:
try:
yield next(g)
except StopIteration:
break
except OSError as e:
# log error
continue
Then wrap your rglob call in the try_loop function
for file in try_loop(pathlib.Path(r'\\path\to\shared\folder').rglob('*.foo')):
pass
This is inspired by a more general question "Handle an exception thrown in a generator".
I have a Python script running on a schedule and I have set up a try/except block to catch all exceptions and email me the exception message so that I can be made aware that something has gone wrong.
I am observing some odd behavior. For every execution of my script, an Exception is being caught where the message is simply:
93
This content is the same when I print it to the console as well.
When I remove the try/except block, there aren't any exceptions being thrown by my code. Does anyone know why the presence of the try/except blocks are causing exceptions and why it is just returning digits?
try:
#do something
except Exception as ex:
s = smtplib.SMTP('000.000.000.000',25)
s.starttls()
s.sendmail('email#email.com', 'email#email.com', 'General Exception in final_parse method ' + str(ex.message))
print str(ex.message)
s.quit()
It depends on what you're doing in your try. The exception is created and raised in that code. It is possible to set an exception's message to 93, or to anything else.
Try evaluating the entire exception in your debugger, or stepping through the code you're running in try until you get the the exception, and look at the context in which it is created/raised. This will at least give you an idea of what the code/module was doing when it failed.
My guess is that the code running in try isn't well written or maintained. Try a different module, or post more details about it here.
Update:
If your stack trace is giving you KeyError, then the code you're executing is throwing a KeyError exception that isn't handled by an except block deeper down in the code, which would mean it's either poorly written or being poorly used. The issue is most likely within your 'do something'
Rather than use smtplib.SMTP you should use Yagmail. It's easier to use:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(emailto, subject = "I now can send an attachment", contents = fileToSend)
I want to know what is the best way of checking an condition in Python definition and prevent it from further execution if condition is not satisfied. Right now i am following the below mentioned scheme but it actually prints the whole trace stack. I want it to print only an error message and do not execute the rest of code. Is there any other cleaner solution for doing it.
def Mydef(n1,n2):
if (n1>n2):
raise ValueError("Arg1 should be less than Arg2)
# Some Code
Mydef(2,1)
That is what exceptions are created for. Your scheme of raising exception is good in general; you just need to add some code to catch it and process it
try:
Mydef(2,1)
except ValueError, e:
# Do some stuff when exception is raised, e.message will contain your message
In this case, execution of Mydef stops when it encounters raise ValueError line of code, and goes to the code block under except.
You can read more about exceptions processing in the documentation.
If you don't want to deal with exceptions processing, you can gracefully stop function to execute further code with return statement.
def Mydef(n1,n2):
if (n1>n2):
return
def Mydef(n1,n2):
if (n1>n2):
print "Arg1 should be less than Arg2"
return None
# Some Code
Mydef(2,1)
Functions stop executing when they reach to return statement or they run the until the end of definition. You should read about flow control in general (not specifically to python)
I'm writing a program that connects to my website via ftp. If the login authentication fails, I want it to continue on to do something else. But an authentication failure error automatically exits the program. Is there a way to ignore this and continue on?
You can use Python's Exception Handling:
try:
do_something()
except Exception, ex:
print "The process failed because", ex
do_something_else()
replace do_something() with code you first want to try.. Replace do_somthing_else() code with what you wish to try when do_something() part fails
Reference for Exception Handling