try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from BaseException, not Exception.
See documentation for details:
trystatement- exceptions
However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?
Answer from vartec on Stack OverflowIs it okay to use try/finally without except?
[SOLVED]How to catch error signals without try / except
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
Is using try/except bad? How to avoid/substitute it.
Videos
try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from BaseException, not Exception.
See documentation for details:
trystatement- exceptions
However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?
It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree it's probably OSError:
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
If you want to silently ignore that error, you would do:
try:
shutil.rmtree(path)
except OSError:
pass
Why? Say you (somehow) accidently pass the function an integer instead of a string, like:
shutil.rmtree(2)
It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.
If you definitely want to ignore all errors, catch Exception rather than a bare except: statement. Again, why?
Not specifying an exception catches every exception, including the SystemExit exception which for example sys.exit() uses:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
Compare this to the following, which correctly exits:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
If you want to write ever better behaving code, the OSError exception can represent various errors, but in the example above we only want to ignore Errno 2, so we could be even more specific:
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
Hi and sorry for the noob question,
I am calling another python script as a subprocess. The python script tries to do X, and if/when it fails it MUST do Y. I had originally been handling this by doing the following:
try:
x
except:
<code to be run>For what I want to do, would it be better to simply use:
try:
x
finally:
yIf I understand correctly, I am basically using except for something finally should be used for at the moment, yes? Is there any downside to not using except for what I want to accomplish?
It depends on whether you can deal with the exceptions that can be raised at this point or not.
If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.
If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.
However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.
The finally block is used for code that must always run, whether an error condition (exception) occurred or not.
The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.
The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.
Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.
Basically I've heard that using try and except is bad as it cultivates bad habits. But I'm not sure how to avoid using these when searching through lists using a "for" loop as it'll give index error otherwise. Basically it tries to check a list (which is the board) whether it has 3 in a row like in tic tac toe, but the board isnt a standard 3x3 and can be whatever and it still successfully detects a 3 in a row.
My code works fine but it includes like 4 separate try and excepts in a for loop which is in another for loop and I'm not sure if thats good
Btw i also dont use except only, I use except IndexError.
If try is technically just a scope marker, it is functionally redundant when scopes are already clear. It is no problem to define a language in which try can be "folded" directly into a preceding scope marker.
For example, it is trivial to treat
while ...
...
catch e
...
as syntactic sugar for
while ...
try
...
catch e
...
which is similar to Ruby's semantics.
Relatedly, if your language is expression based you can have an <expr> catch <name> <expr(name)> construct/operator/... that trivially expands to a longer form. For example, this even was proposed for Python and only rejected for non-technical reasons.
What you should ask yourself is if exception handling for an entire, given scope is actually a good thing. Consider that your tiny example is intended to catch an error from factorial, but actually it would handle two to three things.
To clarify, let me write that part the way I would do for my dayjob:
try:
result = factorial(i)
except e:
print('Factorial of', i, 'resulted in', e.message)
break
else:
print('Factorial of', i, 'is', result)
i += 1
Notice how the factorial handler really only deals with the factorial execution! It does not handle whether formatting strings works, whether printing works, or even whether incrementing works. These are all actions where an error is not expected by your handler, so if one does occur it should absolutely be loud and definitely not accidentally silenced.
Precisely handling errors is something you absolutely do want to offer. And probably (since correct error handling is your goal) you don't just want to offer it, but also encourage it - or even discourage imprecise error handling!
By inviting people to be sloppy and re-use logical scopes as error scopes, you make error handling worse. So at the very least, you should offer something to add explicit scopes. This can be a generic scope mechanism, and in your example syntax it would map to a separate keyword:
while ...
.
.
scope
.
catch e
...
But at this point you are almost all the way to having try, especially if the scope has little or no other use. So basically you have to ask yourself whether you are willing to pay the price of having a try keyword or not - because most if not all of the other cost you should be prepared to pay anyway.
The lack of an explicit try makes it harder to catch exceptions from only some places.
Put together with your other proposal to make exceptions homogeneous, it will be harder in multiple ways for programmers to catch and handle some exceptional cases while allowing others to propagate. It will also be more likely that programmers will mistakenly catch (and accidentally suppress) exceptions they did not intend to.
Consider code like this:
file = acquire_foo()
try:
foo.bar()
foo.baz()
catch:
print('failed to bar and baz the foo')
This shape of code is very common, where we want to acquire a resource and do something with it, and handle the error if the latter fails. Note that the try: specifically occurs after acquire_foo(), meaning if we fail to acquire the resource, the exception will not be caught. This is the programmer's intention, but expressing that intention requires an explicit try. There is no easy way to write this code otherwise.
You could get around this by making catch only apply to the preceding statement, and allowing grouping using optional braces:
foo = acquire_foo()
{ // these together are one statement
foo.bar()
foo.baz()
}
catch:
// this only catches exceptions from the previous block statement
...
However, besides having the same indentation you were trying to avoid by omitting try, this is an accident waiting to happen. People will forget to do this. It's particularly a problem when acquire_foo() and foo.bar() can signal the same type of exception (e.g. a database error), because if you catch from both by accident, you'll mishandle acquire_foo()'s error as if it was thrown by foo.bar().