Search code examples
exceptiontry-catchmultiple-languages

Choosing between if() and try-catch


For example, what should I use when it is necessary to create a column in the table only if such column does not exist?

I can write a code that will check if a column exists doesn't exist, and only then add it, so I can and it without check by wrapping my method in the try-catch (if there is - catch exceptions, and if not - the column will be added)

The result will be the same.

And there are a lot of examples, for example, you can scan files to exist, and only then make a copy, and you can catch exceptions.

Which method is more literate, or the right?


Solution

  • Interestingly enough, your question depends on the programming language you are talking about.

    In languages such as C, Java, C++, C# ... people prefer the "LBYL" (Look Before You Leap) pattern; whereas languages such as python heavily emphasize "EAFP" (it's Easier to Ask for Forgiveness than Permission).

    Meaning: in python, you are using try/catch a lot (even the "counting for loop" is implemented as try/catch); whereas in C#, Java, C++ you would prefer doing if/else instead.

    And these conventions are really important to follow - most Cx-language programmers simply assume that you don't use try/catch to model control flow. In other words: you should follow that paradigm that the majority of other developers in that language would be using.