This means the exception has no message attached. Print the exception type:
print repr(e)
You may also want to print the traceback:
import traceback
# ...
except BaseException as e:
traceback.print_exc()
You want to avoid catching BaseException however, this is no better than a blanket except: statement. Catch more specific exceptions instead.
This means the exception has no message attached. Print the exception type:
print repr(e)
You may also want to print the traceback:
import traceback
# ...
except BaseException as e:
traceback.print_exc()
You want to avoid catching BaseException however, this is no better than a blanket except: statement. Catch more specific exceptions instead.
The following produces a blank line of output:
try:
raise Exception()
except BaseException, e:
print str(e)
Use repr(e) to see what the exception is that was raised.
If you literally want to raise an exception only on the empty string, you'll need to do that manually:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.
If so, open up your interactive interpreter and see what happens when you type things like int('2'), int('abc'), int(''), etc., and the answer should be pretty obvious.
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input() before the try, and check whether user_input is empty within the except. (You put if statements inside except handlers all the time in real code, e.g., to distinguish an OSError with an EINTR errno from one with a different errno.)
try:
input = raw_input('input: ')
if int(input):
......
except ValueError:
if not input:
raise ValueError('empty string')
else:
raise ValueError('not int')
try this, both empty string and non-int can be detected. Next time, be specific of the question.
use str
try:
some_method()
except Exception as e:
s = str(e)
Also, most exception classes will have an args attribute. Often, args[0] will be an error message.
It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.
It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?
Use repr() and The difference between using repr and str
Using repr:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
Using str:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
try:
do_something()
except:
pass
You will use the pass statement.
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
Use pass:
try:
foo()
except:
pass
A pass is just a placeholder for nothing, it just passes along to prevent SyntaxErrors.
So you probably want to print the name of the exception class:
try:
np.arange(1e10)
except Exception as e: #not catch...
print(str(e.__class__.__name__))
print("Catched!")
Using str(e) only prints the "message" of the exception, which in your case was empty.
Note that you can obtain the arguments passed to the exception constructor via the args attribute:
In [4]: try:
...: raise ValueError(1,2,3)
...: except ValueError as e:
...: print('arguments:', e.args)
arguments: (1, 2, 3)
When call str(e) it returns the message of the Exception. Take an example -
NameError: name 'a' is not defined
^ ^
name message
The part before : is the name of the exception, whereas the part after it is the message (arguments).
In the case of MemoryError , as you can see in your example -
MemoryError:
does not have an error message , only the name of the exception , hence you get the empty string.
I am not sure if there are other Exceptions that do not have an exception, but I believe it would be very rare to find such exceptions. Maybe you can print both the exception's name as well as the message , if you really want to take care of the MemoryError (and maybe other such rare exceptions without messages) , something like -
print(type(e).__name__ , ':', str(e))
The function wikipedia.page will raise a wikipedia.exceptions.PageError if the page doesn't exist. That's the error you want to catch.
import wikipedia
links = ["CPython","no page"]
test=[]
for link in links:
try:
#try to load the wikipedia page
page=wikipedia.page(link, auto_suggest=False)
test.append(page)
except wikipedia.exceptions.PageError:
#if a "PageError" was raised, ignore it and continue to next link
continue
You have to surround the function wikipedia.page by a try block, so I'm afraid you can't use list comprehension.
Understand that this will be bad practice, but for a one off quick and dirty script you can just:
edit: Wait, sorry. I've just noticed the list comprehension. I'm actually not sure if this will work without breaking that down:
links = ["CPython", "no page"]
test = []
for link in links:
try:
page = wikipedia.page(link, auto_suggest=False)
test.append(page)
except wikipedia.exceptions.PageError:
pass
test = [testitem.content for testitem in test]
print(test)
pass Tells python to essentially to trust you and ignore the error so that it can continue on about its day.
Method 2 is wrong because you are doing an operation in two steps when it could be done in one. In method 2, you check if the queue is empty, and then later (very soon, but still later), try to get the item. What if you have two threads pulling items from the queue? The get() could still fail with an empty queue. What if an item is added to the queue after you checked that it was empty? These are the sort of tiny windows of opportunity where bugs creep in to concurrent code.
Do it in one step, it's by far the better choice.
import Queue
q = Queue.Queue()
try:
task = q.get(False)
except Queue.Empty:
# Handle empty queue here
pass
else:
# Handle task here and call q.task_done()
Don't get hung up on "exceptions should be errors". Exceptions are simply another channel of communication, use them. Use the "else" clause here to narrow the scope of the exception clause.
If this is multithreaded / multiprocessed code (as is a good reason for using queues anyway), then definitely method 1. Between the q.empty() call and the q.get() call, the Jack of Hearts could have stolen your tarts!
The recommendation in Python is to use exceptions to indicate failure. This is true even if you expect failure on a regular basis.
Look at it from the perspective of the caller of your code:
my_status = get_abe_status(my_url)
What if we return None? If the caller doesn't specifically handle the case that get_abe_status failed, it will simply try to continue on with my_stats being None. That may produce a difficult to diagnose bug later on. Even if you do check for None, this code has no clue why get_abe_status() failed.
But what if we raise an exception? If the caller doesn't specifically handle the case, the exception will propagate upward eventually hitting the default exception handler. That may not be the what you want, but its better then introducing a subtle bug elsewhere in the program. Additionally, the exception gives information about what went wrong which is lost in the first version.
From the caller's perspective, its simply more convenient to get an exception than a return value. And that's the python style, to use exceptions to indicate failure conditions not return values.
Some will take a different perspective and argue that you should only use exceptions for cases you never really expect to happen. They argue that normally running running could should not raise any exceptions. One reason that is given for this is that exceptions are grossly inefficient, but that's not actually true for Python.
A couple of points on your code:
try:
hits[0]
except IndexError:
raise NotFoundError("No mentions found.")
That's a really confusing way to check for an empty list. Don't induce an exception just to check something. Use an if.
# say we expect four hits...
if len(hits) != 4:
raise Warning("An unexpected number of hits.")
logger.warning("An unexpected number of hits.")
You do realize that the logger.warning line will never run right?
The accepted answer deserves to be accepted and answers the question, I write this only to provide a bit of extra background.
One of Python's credos is: it's easier to ask forgiveness than permission. This means that typically you just do things, and if you expect exceptions, you handle them. As opposed to doing if checks before hand to make sure you won't get an exception.
I want to provide an example to show you how dramatic the difference is in mentality from C++/Java. A for loop in C++ typically looks something like:
for(int i = 0; i != myvector.size(); ++i) ...
A way to think about this: accessing myvector[k] where k >= myvector.size() will cause an exception. So you could in principle write this (very awkwardly) as a try-catch.
for(int i = 0; ; ++i) {
try {
...
} catch (& std::out_of_range)
break
Or something similar. Now, consider what's happening in a python for loop:
for i in range(1):
...
How is this working? The for loop takes the result of range(1) and calls iter() on it, grabbing an iterator to it.
b = range(1).__iter__()
Then it calls next on it at each loop iteration, until...:
>>> next(b)
0
>>> next(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
In other words, a for loop in python is actually a try-except in disguise.
As far as the concrete question goes, remember that exceptions stop normal function execution and must be dealt with separately. In Python, you should freely throw them whenever there is no point executing the rest of the code in your function, and/or none of the returns correctly reflect what happened in the function. Note that returning early from a function is different: returning early means you already figured out the answer and don't need the rest of the code to figure out the answer. I am saying that exceptions should be thrown when the answer is not known, and the rest of the code to determine the answer cannot be reasonably run. Now, "correctly reflect" itself, like which exceptions you choose to throw, is all a matter of documentation.
In the case of your particular code, I would say any situation that causes hits to be an empty list should throw. Why? Well, the way your function is setup, there is no way to determine the answer without parsing hits. So if hits is not parseable, either because the URL is bad, or because hits is empty, then the function can't answer the question, and in fact can't even really try to.
In this particular case, I would argue that even if you manage to parse and don't get a reasonable answer (alive or dead), then you should still throw. Why? Because, the function returns a boolean. Returning None is very dangerous to your client. If they do an if check on None, there won't be failure, it will just silently be treated as False. So, your client will basically always have to do an if is None check anyhow if he doesn't want silent failures... so you should probably just throw.