try:
do_something()
except:
pass
You will use the pass statement.
Answer from Andy on Stack OverflowThe pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
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.
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.
I think you are accurate about the trade-off involved - neither is ideal. Out of those two, I personally prefer the first one since the control flow is easier to follow.
That said, I'd suggest considering a third option that you didn't mention: factor out some or all of the recovery logic into a separate function. That keeps the control flow simple and avoids having a big block of recovery code in the except clause.
Explicit is better than implicit.
If you are handling an exception, handle it. Right there, right then.
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.
Okey, so there a few things that need to be explained where.
What is try-except used for?
It is used for catching errors raised by the program. Any code susceptible of raising an exception is inserted inside a try statement, and below that statement, any number of except statements with any single error that you want to catch.
try:
user_input = int(input('Give me a number: '))
except ValueError:
print('That is not a number!')
When should i use try-except?
It is not a good practice to use a try-except on every single line of code that could raise an error, because that may be half of it, or more. So when shall you use it? Simple, ask this question: Do I want to do any custom action with that error being raised? If the answer is yes, you are good to go.
Catching Exception or empty except
As I see in your example, you are using an empty except. Using an empty except statement will catch every single error raised that the surrounded code, which is similar (but not the same) as catching Exception. The Exception class is the superclass of every single built-in exception in the Python environment that are non-system-exiting (read here) and its generally a bad practice to catch either all exceptions with except: or Exception with except Exception:. Why? Because you are not letting the user (or even you, the programmer) know what error you are handling. For example:
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except Exception:
print('Error!')
# But wait, are you catching ValueError because the user did not input a number,
# or are you catching IndexError because he selected an out of bound array index?
# You don't know
Catching multiple exceptions
Based on the previous example, you can use multiple try-except statements to difference which errors are being raised.
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except ValueError:
print('That is not a number')
except IndexError:
print('That fruit number does not exist!')
Grouping exceptions
If there are two particular exceptions that you want to use for a same purpose, you can group them in a tuple:
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except (ValueError, IndexError):
print('Invalid selection!')
Your case
Based on this information, add those try-except blocks to your code, and see what possible errors that could be raised during its execution, asking the previously recommended question Do I want to execute some custom action with this error?
Additionally
- There are
try-except-elsestatements. See here - There are
try-except-finallystatements. See here - You can combine them all in a
try-except1-except2...exceptN-else-finallystatement. - I recommend you get familiar with built-in errors why practicing this!
try: code that might cause an errorexcept: code that runs if an error happenselse: runs if no error happensfinally: always runs (good for cleanup, closing files, etc.)
Example 1: Basic Example
try:
num = int("abc") # This will raise an error
print("Number:", num)
except ValueError:
print("Oops! Could not convert to int.")
Example 2:
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid value!")
Example 3:
try:
x = 5 / 1
except ZeroDivisionError:
print("Division by zero not allowed.")
else:
print("Division successful:", x) # runs if no error
finally:
print("Always runs, even if there was an error.")
Example 4: General
try:
# risky code
x = 10 / 0
y = int("abc")
except Exception as e:
print("Error occurred:", 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.
Just write
pass
as in
try:
# Do something illegal.
...
except:
# Pretend nothing happened.
pass
EDIT: @swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say
except TypeError, DivideByZeroError:
or whatever kinds of errors you want to handle. Otherwise you can mask bigger problems.
For those who are very unclear as to why you would want to do this. Here is an example where I initially thought that an empty block would be a good idea:
def set_debug_dir(self, debug_dir=None):
if debug_dir is None:
debug_dir = self.__debug_dir
elif isinstance(debug_dir, (Path, str)):
debug_dir = debug_dir # this is my null operation
elif isinstance(debug_dir, list):
debug_dir = functools.reduce(os.path.join, debug_dir)
else:
raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
But it would be more clear to reorganize the statement:
def set_debug_dir(self, debug_dir=None):
if debug_dir is None:
debug_dir = self.__debug_dir
elif isinstance(debug_dir, list):
debug_dir = functools.reduce(os.path.join, debug_dir)
elif not isinstance(debug_dir, (Path, str)):
raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
You use python3 and in python3 the raise syntax no longer accepts comma-separated arguments.
Use as instead:
except getopt.GetoptError as e:
This form is also backwards-compatible with 2.6 and 2.7.
Your syntax is invalid for catching the exception
You should have written except getopt.GetoptError as e: instead of except getopt.GetoptError, e:
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
Either drop the except Block, or improove it really by adding
except [Exception-Class]:
pass
where [Exception-Class] is the exception to be excepted. This adds some sugar on it, because really unexpected Errors are not getting catched by this. (Or add this as a seperate:
except Exception, ex:
print "Unexpected error:", ex
Yes, you can drop the except block completely, it is a valid python syntax to have just try and finally . Example -
In [58]: try:
....: print("Blah")
....: finally:
....: print("halB")
....:
Blah
halB
Please note this will not catch any Exceptions/Errors that occur within the try block, and I am guessing that is what you want.
I have seen this used at quite some places, where we are creating some variables/resources that need to be cleared irrespective of whether any exceptions/errors occur, but we do not want to handle any Exceptions at that particular place.