-1

Often, I come across cases where I find both if-else and try-except clauses can be used to solve a problem. As a result, I have some confusion deciding(and justifying) the use of a particular clause to accomplish the task at hand.
For example, let us consider a trivial situation:

In []: user = {"name": "Kshitij", "age": 20 }

# My motive is to print the user's email if it is available.
# In all other cases, a warning message needs to be printed

# Method-01 : Using try clause
In []: try:
  ...:     print(a["email"])
  ...: except KeyError:
  ...:     print("No EMAIL given")
  ...:     
No EMAIL given

# Method-02 : Using if-else clause
In []: if "email" in a:
           print(a["email"])
  ...: else:
  ...:     print("No EMAIL given")
  ...:     
No EMAIL given

I would like to know how can I decide a more Pythonic method among the two and justify it. Also, some pointers to how can one differentiate among several methods to solve similar scenarios would be really helpful.

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
  • This doesn't answer your question, but third alternative: `print(a.get("email", "No EMAIL given"))` ;-) – Kevin Jan 11 '17 at 19:42
  • I don't think this is a duplicate. In my opinion, this is an amalgamation of all such cases. I just happened to give an example which is related to another question. – Kshitij Saraogi Jan 11 '17 at 19:48
  • @Kevin Won't you agree with me if I say that "getting" `No EMAIL given` is a bad Pythonic construct since the motive here is not to "get" it, rather display it ? – Kshitij Saraogi Jan 11 '17 at 19:50

4 Answers4

2

try/catch and if/else are not interchangeable. the former is for catching errors that might be thrown. no if statement can do that. if/else is for checking if a condition is true or false. errors thrown in an if/else block will not be caught and the program will crash.

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

You should use exceptions if this case is an exception and not the normal case.

Daniel
  • 42,087
  • 4
  • 55
  • 81
0

if/then: for internal application flow control. Errors are unlikely to be fatal

vs

try/except: for system calls and API calls where the state of the receiver is external to the code. Failures are likely to be fatal and need to handled explicitly

Manager_of_it
  • 96
  • 1
  • 6
0

If you're looking for "Pythonic", neither of those is.

print a["email"] if "email" in a else "No EMAIL given"

Now that's Pythonic. But, back to the question: First of all, you decide what to do - I'm not aware of any writing conventions between those two. But, as I see it:

if-else is used mainly for detecting expectable behaviour - I mean, if "email" is not in a, it's excpectable. So we will use if-else.
An example would be your code.

But, for example, if we want to check if a string contains a numeric value, we will try to convert it to a number. If it failed, well, it's a bit harder to predict it using an if statement, so we will use try-except.
Here's a short example for that:

def is_numeric(string):
    try:
        a = float(string)
        return True
    except:
        return False
  • of course there is a better way to check if a string is numeric, that was just an example use of try-except.
Yotam Salmon
  • 2,400
  • 22
  • 36