When do you use each? I find that I'm using if's a lot more than exceptions. It seems like I'm catching t开发者_如何转开发he 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),- the
with
statement (specific to Python), - the RAII paradigm which involves cleanup in destructors (mostly C++).
Especially as you work with large applications, exception handling really is a better practice. As you mentioned, you are getting a lot of if statements. With python, using try/except statements allows you to create a more standardized way of dealing with exceptions. With exceptions, you'll get the benefit of seeing the type of exception class as well as any other custom ones you build. It just gives you a much more structured way of coding.
精彩评论