Python try except - python

try:
#statement 1
#statement 2
except Exception, err:
print err
pass
This may be very trivial but I never actually thought about it until now and I found myself not being able to answer the following questions:
Does statement 2 gets executed if an error is raised in statement 1?
How does Exception deal with in a case where an error is raised for both statement 1 and statement 2? Which error does it print out in the above code? Both?

The answer is "no" to both of your questions.
As soon as an error is thrown in a try/except block, the try part is immediately exited:
>>> try:
... 1/0
... print 'hi'
... except ZeroDivisionError, e:
... print 'error'
...
error
>>>
As you can see, the code never gets to the print 'hi' part, even though I made an except for it.
You can read more here.

From Python docs:
If an exception occurs during execution of the try clause, the rest of
the clause is skipped. Then if its type matches the exception named
after the except keyword, the except clause is executed, and then
execution continues after the try statement.
So as soon as an error occurs, it skips to the exception
http://docs.python.org/2/tutorial/errors.html

Upon an exception being raised control leaves the try block at the point the exception is raised and is given to the appropriate except block. If statement 1 throws an exception, statement 2 will not execute.
This answers your second question as well: it's not possible for the scenario you describe to happen.

1) Does statement 2 gets executed if an error is raised in statement 1?
No. Exception will be raised and catched.
As I understand python will move up the stack and looks for an exception handler in the caller
2) How does Exception deal with in a case where an error is raised for both statement 1 and statement 2? Which error does it print out in the above code? both?
statement 2 will not be run so no exceptions will be raised for it
any exception from the try block will be caught. That is why for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

1) Does statement 2 gets executed if an error is raised in statement
1?
nope, statement 2 is not executed
2) How does Exception deal with in a case where an error is raised for
both statement 1 and statement 2? Which error does it print out in the
above code? both?
only statement 1 has a chance to raise an error, see above,
NOTE: if you want statement 2 to execute always, you can use finally with the try/except

Related

Does a try except stop right away in python if an exception is found?

If I have a try except block in my python code, and the first line of my try statement raises an exception will it automatically move on to exception or will it finish the try block first?
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
Here is it checking if it can int(string), which it can't, and then it immediately moves onto except, or does it do the string assignment first?
When I run it, it seems like it stops right away, but I want to know if that's happening for sure or something else.
Thanks
Let's try it.
try:
1/0
print("what?")
except:
print("nope")
Output:
nope
>>>
When an exception is raised it moves on to the except.
From the python docs, I found this,
"The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above."
Cheers!
Hope it helps!
#the try block is to run the process
try:
string = "This was a mistake, can't int string"
#you are parsing the string into an int
int(string)
#this block is to capture the exception when it is raised
except:
#here I am just printing the exception
print('Exception')
#the pass is to pass the execution and follow the remaining process.
pass
Output:
Exception
>>>
Well, that the whole point of an error handler. When an error occurs in out program, it crashes, it won't simply skip the error line.
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
So if the try block finishes even after an error occurred in the middle, then the error handler'd seem a bit pointless.
There seem to be some issue with your program and maybe your understanding of the try except block.
First of all, from the block of code you have provided, it seems to me like string isn't even defined yet when you try to pass int(string).
Secondly, the string variable which you seem to be defining under seems to me like is something you are trying to print to the console once the program spits out an error and passes to the except block. If this is what you are trying to do, then your code should look something like this:
try:
int(string)
except:
print("This was a mistake, can't int string")
If you were to run the code provided above, you would indeed confirm that the try except statement is working as it would print "This was a mistake, can't int string" into the console instead of giving an error. Hope this was somewhat helpful and understandable. You got this chief, keep grinding!

How the ZeroDivisionError process

I would like to know what is the use of ZeroDivisionError and how it works in the following example code?
try:
hopCounts.append(flow_stats.timesForwarded/ flow_stats.rxPackets)
except ZeroDivisionError:
flow_stats.jitterSum.GetSeconds() == 0
For the code-sample you gave:
try:
# try block
hopCounts.append(flow_stats.timesForwarded / flow_stats.rxPackets)
except ZeroDivisionError:
# exception block
flow_stats.jitterSum.GetSeconds() == 0
The try block will run the code inside the brackets first flow_stats.timesForwarded / flow_stats.rxPackets.
If flow_stats.rxPackets is zero, then the ZeroDivisionError exception will be raised.
Otherwise, the value calculated will be appended to the hopCounts list.
The exception block will not be executed.
If the ZeroDivisionError exception was raised, that exception will be caught by the except statement, and the exception block code will run
flow_stats.jitterSum.GetSeconds() == 0
However, that code won't do anything, it will simply return True or False... it has the same effect as simply writing True in python on a line by itself.
To learn more, read http://www.pythonforbeginners.com/error-handling/exception-handling-in-python
Divide by Zero is not limited to any language, this exception occurs at the machine/processor level. When processor detects 'DivideByZero' it throws a DivideByZero exception, whose handlers are already inside the operating system code.
Exception handler provided by user at application level (whether in C++, python or any other high level language) are barely a recovery path for that application should such exception occur.

Is finally in Python added just for better readability

On this link (https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions) following is said:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
CODE 1:
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 1:
Performing an action which may throw an exception.
Everything looks great!
Finally is called directly after executing the try statement whether an exception is thrown or not.
CODE 2:
try:
print "Performing an action which may throw an exception."
raise Exception('spam', 'eggs') # This is new
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
OUTPUT 2:
Performing an action which may throw an exception.
An exception was thrown!
('spam', 'eggs')
Finally is called directly after executing the try statement whether an exception is thrown or not.
What I get from this is that else is executed only when there is no exception.
QUESTION:
Is finally used just for better readability ?
Because I can just put this print statement after try, like in this code.
CODE 3:
try:
print "Performing an action which may throw an exception."
#raise Exception('spam', 'eggs') # with this line or without last print is done
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
There are circumstances where the finally suite is always executed, but your print statement would not:
When there is an unhandled exception in your try.
When your try is in a loop (while or for) and you used a break or continue statement
When your try is in function and you used a return statement.
The finally suite then is used to guarantee that code is executed, regardless of what happens in the try block, even when exited before reaching the end of the block.
Compare:
def foo():
try:
print "Performing an action which may throw an exception."
return
except Exception as error:
print "An exception occured!", error
finally:
print "Cleaning up"
with
def bar():
try:
print "Performing an action which may throw an exception."
return
except Exception as error:
print "An exception occured!", error
print "Cleaning up"
In bar() the last message is not printed:
>>> foo()
Performing an action which may throw an exception.
Cleaning up
>>> bar()
Performing an action which may throw an exception.
The finally code block is always executed, whether or not an exception is thrown. This is true in most (I wanted to say all but ...) other languages: C#, Java, etc.
Its function is to allow the execution of clean-up code -- close opened resources, de-allocate memory, etc. -- for the program to continue/terminate its execution in a clean and safe way.

Stop Python code without an error

I have a piece of code which is not in a function, say
x = 5
y = 10
if x > 5:
print("stopping")
What can I put after the print statement to stop the code from running further? Sys.exit() works, but raises an error that I don't want in the program. I want it to quietly stop the code as if it had reached the end of the main loop. Thanks.
As JBernardo pointed out, sys.exit() raises an exception. This exception is SystemExit. When it is not handled by the user code, the interpreter exits cleanly (a debugger debugging the program can catch it and keep control of the program, thanks to this mechanism, for instance)—as opposed to os._exit(), which is an unconditional abortion of the program.
This exception is not caught by except Exception:, because SystemExit does not inherit from Exception. However, it is caught by a naked except: clause.
So, if your program sees an exception, you may want to catch fewer exceptions by using except Exception: instead of except:. That said, catching all exceptions is discouraged, because this might hide real problems, so avoid it if you can, by making the except clause (if any) more specific.
My understanding of why this SystemExit exception mechanism is useful is that the user code goes through any finally clause after a sys.exit() found in an except clause: files can be closed cleanly, etc.; then the interpreter catches any SystemExit that was not caught by the user and exits for good (a debugger would instead catch it so as to keep the interpreter running and obtain information about the program that exited).
You can do what you're looking for by doing this:
import os
os._exit(1)
sys.exit() which is equivalent to sys.exit(0) means exit with success. sys.exit(1) or sys.exit("Some message") means exit with failure. Both cases raise a SystemExit exception. In fact when your program exists normally it is exactly like sys.exit(0) has been called.
When I ran across this thread, I was looking for a way to exit the program without an error, without an exception, have the code show as 'PASSED', and continue running other tests files. The solution, for me, was to use the return statement.
.
.
.
if re.match("^[\s\S]*gdm-simple-slave[\s\S]*$", driver.find_element_by_css_selector("BODY").text) == None:
print "Identifiers object gdm-simple-slave not listed in table"
return
else:
driver.find_element_by_xpath("//input[#value='gdm-simple-slave']").click()
.
.
.
That allowed me to run multiple programs while keeping the debugger running...
test_logsIdentifiersApache2EventWindow.py#16::test_LogsIdentifiersApache2EventWi
ndow **PASSED**
test_logsIdentifiersAudispdEventWindow.py#16::test_LogsIdentifiersAudispdEventWi
ndow **PASSED**
test_logsIdentifiersGdmSimpleSlaveEventWindow.py#16::test_LogsIdentifiersGdmSimp
leSlaveEventWindow Identifiers object gdm-simple-slave not listed in table
**PASSED**
test_logsIdentifiersAuditdEventWindow.py#16::test_LogsIdentifiersAuditdEventWind
ow **PASSED**
Use try-except statements.
a = [1, 2, 3, 4, 5]
for x in xrange(0,5):
try:
print a[x+1] #this is a faulty statement for test purposes
except:
exit()
print "This is the end of the program."
Output:
> python test.py
2
3
4
5
No errors printed, despite the error raised.

What's the scope of using the 'finally' clause in python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Purpose of else and finally in exception handling
I'd like to understand why the finally clause exists in the try/except statement. I understand what it does, but clearly I'm missing something if it deserves a place in the language. Concretely, what's the difference between writing a clause in the finally field with respect of writing it outside the try/except statement?
The finally suite is guaranteed to be executed, whatever happens in the try suite.
Use it to clean up files, database connections, etc:
try:
file = open('frobnaz.txt', 'w')
raise ValueError
finally:
file.close()
os.path.remove('frobnaz.txt')
This is true regardless of whether an exception handler (except suite) catches the exception or not, or if there is a return statement in your code:
def foobar():
try:
return
finally:
print "finally is executed before we return!"
Using a try/finally statement in a loop, then breaking out of the loop with either continue or break would, again, execute the finally suite. It is guaranteed to be executed in all cases.
The finally clause will always execute which is great if you missed an exception type in your code.
To quote the documentation:
If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally clause.

Categories

Resources