Handling Exceptions in Python 3.6 - python

I am trying to handle exceptions in Python 3.6. I want to handle every possible exception and print the exception. When i do
try:
raise RuntimeError("Test")
except:
e = sys.exc_info()[0]
print(e)
it just prints
class '_mysql_exceptions.OperationalError'
How do i get the message of the Exception? In this case i would like the output to be "Test".

You can catch and print the Exception as follows:
try:
raise RuntimeError("Test")
except Exception as e:
print(e)
# Test
I'm not quite sure why you're trying to catch every Exception though, it would seem more prudent to let Python handle and raise these for you in general. Normally you would only catch specific Exceptions.
This behavior is not specific to Python 3.6.

Related

Create custom exceptions?

Is there a way to shorten the following scenario so i don't have to use an ugly nested try except statement?
class Error(Exception):
def __init__(self):
print("That did not work")
try:
try:
gblgbl
except:
raise Error
except Error:
pass
What i want can be described as following pseudo code:
Try something:
something
if something went wrong:
raise Error
catch Error:
what to do if error occours
I don't want to raise the error if the try statement succeeds, however if i raise an exception in the exception statement like this:
try:
gblgbl
except:
raise Error
except Error:
pass
it can't be caught with an other except, since there is already an except that caught the python exception and the interpreter throws a SyntaxError.
Am i missing something obvious?
I'm aware that you probably would never use this in an actual program, but i'm curious about the theory.
There is no reason to use an exception here. The following (pseudo-)code achieves the same thing.
try:
gblgbl
except:
pass
Note however that it generally is a bad idea to catch all exceptions, since for instance the KeyboardInterrupt Exception will also be caught and the program can thus not be interrupted using Ctrl-c
Create custom exceptions?
The Python Tutorial has a section on User-defined Exceptions

What's the difference between "KeyError" and "KeyError as e"?

When writing try/except statements, whether I use
except KeyError:
or
except KeyError as e:
I get the same result.
What is the difference between the two? Is KeyError as e just more specific/custom?
When using except KeyError as e:, you can access the exception and its attributes as an object with e. Like so:
def test_function():
try:
do_something_that_fails()
except Exception as e:
print e.message, e.args
It will help with debugging any problems you have when the exception is thrown.
You can find more information on how this works in the Python Documentation.
Good luck!

Can't catch SystemExit exception Python

I am trying to catch a SystemExit exception in the following fashion:
try:
raise SystemExit
except Exception as exception:
print "success"
But, it doesn't work.
It does work however when I change my code like that:
try:
raise SystemExit
except:
print "success"
As far as I am aware, except Exception as exception should catch any exception. This is how it is described here as well. Why isn't that working for me here?
As documented, SystemExit does not inherit from Exception. You would have to use except BaseException.
However, this is for a reason:
The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.
It is unusual to want to handle "real" exceptions in the same way you want to handle SystemExit. You might be better off catching SystemExit explicitly with except SystemExit.

handling exceptions from mechanize in python 2.7

I have a small script that uses mechanize to go to a few websites to collect data. Sometimes the websites cause the script the crash and returns either "Bad Gateway" or "Connection Reset By Peer". I have an except line in the code so it emails me if there are any problems with the program, but I am trying to find a way to have it NOT email me in the case of these 2 problems. I've tried:
except Exception as e:
if 'Gateway' not in e and 'peer' not in e:
logger.error(e)
But this doesn't seem to work, as i still get emails if one of these 2 errors occur. What is the best way to have it email me in the case of any exception except for exceptions that contain certain text?
Instead of e in your if statement, use str(e).
except Exception as e:
if 'Gateway' not in str(e) and 'peer' not in str(e):
logger.error(e)

What happens exactly internally when I terminate my Python script using Ctrl+c?

These days I am learning Python's Exception handling features deeply. I encountered exception SystemExit. While reading about this from official Python Docs I got question in mind that what exactly would have happen when I terminate Python script by pressing Ctrl+c?
lets take this sample code:
def func1(a,b):
print "func1: "+str(a/b)
#some more functions
def func2(a,b):
print "func2: "+str(a/b)
#some more functions
if __name__=="__main__":
import random
count=0
for i in range(1000000):
count=count+1
print "count: "+str(count)
try:
func1(random.randint(-2,3),random.randint(-2,3))
except KeyboardInterrupt:
raise
except:
print "error in func1"
try:
func2(random.randint(-2,3),random.randint(-2,3))
except KeyboardInterrupt:
raise
except:
print "error in func2"
print "\n"
In this sample code I am catching KeyboardInterrupt so I can stop my script by pressing Ctrl+c. Should I catch SystemExit too to make this code more mature? if yes then why? actually this question is source of my main question which appear on title. so don't consider that I am asking two different question in one post.
You usually not need to catch SystemExit as it is what makes exit() and sys.exit() functions work:
sys.exit([arg])
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
Example:
try:
exit()
except SystemExit:
print "caught"
Therefore, you usually don't want to catch all exceptions in the first place (by using an empty except: clause). The best approach is generally to make your exception handlers as specific as possible. It otherwise makes debugging your application exceptionally hard, as it either hides errors entirely or at least makes it hard to diagnose the details.
The only exception your functions can raise is a ZeroDivisionError, so you should only catch that one:
import random
if __name__ == "__main__":
for count in range(1000000):
print "count:", count
try:
func1(random.randint(-2, 3),random.randint(-2, 3))
except ZeroDivisionError:
print "error in func1"
try:
func2(random.randint(-2, 3),random.randint(-2, 3))
except ZeroDivisionError:
print "error in func2"
print "\n"
Your title says something different than the body of your question.
To the title:
What happens internally is that python captures the SIGINT and raises a KeyboardInterrupt exception from it.
To the text:
You don't want to do except:.
Instead, you want
if __name__=="__main__":
try:
import random
count=0
for i in range(1000000):
count=count+1
print "count: "+str(count)
try:
func1(random.randint(-2,3),random.randint(-2,3))
except Exception, e:
print "error in func1", e # or something...
try:
func2(random.randint(-2,3),random.randint(-2,3))
except Exception, e:
print "error in func2", e # or something...
print "\n"
except Exception:
raise # any other "normal" exception.
except: # Here it is ok, as you handle most exceptions above.
pass
Most "normal" exception which should normally be handled derive from Exception. Those which have an internal meaning and should normally not be caught (except on global level) don't derive from Exception.
These are KeyboardInterrupt, SystemExit and GeneratorExit.
If you're uncertain what exceptions the code you're calling throws to indicate errors then you should (in order of preference):
Find out what it is documented to throw and only catch that
catch Exception, not everything.
Neither KeyboardInterrupt nor SystemExit is a subclass of Exception, but all of the standard Python exceptions used to indicate errors are.

Categories

Resources