Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you check for errors using "if" , and when should you use exceptions? [duplicate]

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.

like image 420
TIMEX Avatar asked Jan 13 '11 05:01

TIMEX


3 Answers

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.

like image 77
Johnsyweb Avatar answered Oct 08 '22 03:10

Johnsyweb


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.

like image 43
Nickz Avatar answered Oct 08 '22 04:10

Nickz


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++).
like image 26
Kos Avatar answered Oct 08 '22 04:10

Kos