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.
Related
I've recently had a problem when coding in Python in the PyCharm editor. Whenever I made a try-except statement, I would for some reason get a warning (yellow line beneath the word: except)
Here is an example:
s = "Text"
try:
print(s[2])
except:
print("There is no character at that index")
When I write this exact code in PyCharm, I get a warning. When I hover my mouse over the warning it says:
Too broad exception clause
PEP 8: E722 do not use bare 'except'
Any idea why this happens?
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
For example:
try:
import platform_specific_module
except ImportError:
platform_specific_module = None
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).
A good rule of thumb is to limit use of bare 'except' clauses to two cases:
If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a better way to handle this case.
This appeared to be a very obvious yet annoying issue.
Consider the code block here -
for i in tqdm.notebook.tqdm(range(int(3*len(structures)/4))):
try:
is_mal=np.array([1.]) if 'Malware' in structure_info[i] else np.array([0.])
target=parse_Structure(file=structures[i])
target=np.reshape(target.get_vector(),(-1,1))
is_mal=np.reshape(is_mal,(-1,1))
vectors=np.concatenate((vectors,target), axis=1)
labels=np.concatenate((labels,is_mal), axis=1)
except:
print(i)
The code does not matter anyways. But I have a simple question.
While running this on my Colab Notebook environment online, when I wanted to debug for something in the middle of the loop, I simply tried to interrupt execution.
This resulted in printing of the index i the loop was at, obviously the interrupt was being considered as an exception. While I do agree with the fact the loop is executing try-catch block perfectly, I also want to interrupt the execution badly.
How do I interrupt execution of this block without restarting the runtime?
You can raise a new exception inside the except block to pass it onwards:
try:
<code>
except:
raise Exception
If you want to reraise the same exception that was caught:
try:
<code>
except Exception as E:
raise E
This will pass the exception on to the next handler, If there is no other try/excepts, it will halt the whole script.
If you are interrupting by something that is not caught by Exception (for example Ctrl-C), you can replace Exception with either BaseExceptionor KeyboardInterrupt. Note that these two latter should rarely be blanket caught and not reraised in a production environment, as that could make it a hassle to actually exit the program again.
More info on exceptions: https://docs.python.org/3/library/exceptions.html
I give following code snippet,
As at the end of the code I am getting blank output file
in with context when exception is raised The file is closed and again overridden in next iteration
with open('output', 'w') as f:
try:
for i in range(1, 100):
if i % 2 == 0:
f.write('%d \n' % i)
else:
raise Exception()
except Exception as e:
pass
Is my understanding correct?
If so, Why this behavior is there?As I am handling the exception.
Is it right that with statement will always close files
whenever exception is raised in side block.
What could be possible solution using with statement?
When using a try/except block, the try block is not continued upon completion of the except block.
A possible solution would be to replace the raise Exception() statement - which is currently raising a meaningless exception - with a pass statement instead.
In fact, you should probably do a little reading regarding when to use exceptions.
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
I'm aware that it's possible to ignore exceptions in Python using try...except statements. Is it possible to ignore exceptions in Python when they occur, but still print them?
I tried ignoring the exception here, and therefore, the exception was not printed when it was encountered:
try:
num = 0
if num == 0:
raise Exception("Num must not be 0!")
except Exception:
pass
'''The exception is ignored, and is not printed.'''
I've written a simple source-to-source compiler that has a lot of exceptions like these, and I'm not sure how I can ignore the exceptions while still printing them. How can I ensure that the exceptions are printed to the console even when they are being ignored?
You can print an exception like this.
try:
x = 1 / 0
except Exception as e:
print e
EDIT:
As user1354557, gcbirzan, and Jonathan Vanasco pointed out, you can use the traceback and logging modules to get more precise error messages. Error messages printed out these ways will be more verbose, which is (usually) a good thing.
import traceback
try:
x = 1 / 0
except Exception as e:
print traceback.format_exc() # I prefer this to traceback.print_exc()
import logging
try:
x = 1 / 0
except Exception as e:
logging.exception(e)
If you want a printout of the stack trace, you can use the traceback module:
import traceback
try:
0/0
except:
traceback.print_exc()
This would print something like:
Traceback (most recent call last):
File "example.py", line 3, in <module>
0/0
ZeroDivisionError: integer division or modulo by zero
Is this what you're looking for?
You should take a look at the logging module. It has support for logging exceptions with traceback (either via logger.exception or by passing exc_info as a keyword parameter to any logging function).
By ignore, I suppose you mean you want to print it, but not catch it, and allow it to bubble up the call stack. You can do that by catching the exception, printing it, and then re-throwing it.
try :
# do something
except Exception as e:
print e
raise e
It's possible to do this globally, even in code you didn't write (such as a library module) using a trace function.
import sys
def print_exceptions(frame, event, arg):
if event == "exception":
sys.excepthook(*arg)
return print_exceptions
sys.settrace(print_exceptions)
Note that the trace function is called for every statement executed while it is in effect and may therefore significantly slow down your script's execution. Another minor issue is that any unhandled exception will be printed twice (once by this hook, again by Python itself when exiting the script).
If you want to customize the output, you can dig the information you want out of arg (it's a 3-tuple of the exception type, the error message, and a traceback object) and frame (which includes a reference to the current code object, from which its name can be obtained, as well as the source filename and line number).