When do you use each? I find that I'm using if's a lot more than exceptions. It seems like I'm catching the exceptions using my "ifs", before I even get them. There are ifs all over my code.
EAFP: Easier to ask for forgiveness than permission.
It is common Python coding style to assume the existence of valid keys or attributes and catch exceptions if the assumption proves false.
This contrasts with the LBYL (Look before you leap) style common to many other languages such as C.
Update 1
Of course, you must ensure you handle any caught exceptions and not just silently ignore them otherwise you're going to waste a lot of time debugging! pass
is probably not what you are looking for!
Update 2
You should catch the specific exceptions that you are expecting to be raise
-d, whether they are built-in exceptions or otherwise.
Try catch statements are designed to handle serious errors and particularly for connecting to outside service such as a web service, Database, web Request and etc. where errors will and are expected to happen from time-to-time. It’s heavier on runtime environment to handle an exception, than for you to write good code and utilising the given language’s features such ifs or ternary operation.
try catches are not the first line of defense, they are the last line using defensive coding practises.
I'm not repeating what many people have already said, but there's a big advantage of using exceptions which I'd like to mention:
If some routine fails, you can easily decide on which level of indirection you should handle that exception - and you won't need to bloat the deeper levels with error checking after, say, each step.
Of course that doesn't free you from the responsibility of having good cleanup code which will leave everything clear for every possible path of execution: so release any resources, sockets, commit or rollback transactions, etc. And there are many means to do that:
try... finally
blocks, allowing any exception to propagate but cleaning everything up before (many languages, including Python),with
statement (specific to Python),If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With