Is it better to use an exception or a return code in Python?

后端 未结 6 2165
执念已碎
执念已碎 2020-12-13 06:08

You may know this recommendation from Microsoft about the use of exceptions in .NET:

Performance Considerations

...

Throw exc

6条回答
  •  借酒劲吻你
    2020-12-13 06:41

    The best way to understand exceptions is "if your method can't do what its name says it does, throw." My personal opinion is that this advice should be applied equally to both .NET and Python.

    The key difference is where you have methods that frequently can't do what their name says they should do, for instance, parsing strings as integers or retrieving a record from a database. The C# style is to avoid an exception being thrown in the first place:

    int i;
    if (Int32.TryParse(myString, out i)) {
        doWhatever(i);
    }
    else {
        doWhatever(0);
    }
    

    whereas Python is much more at ease with this kind of thing:

    try:
        i = int(myString)
    except ValueError:
        i = 0
    doWhatever(i);
    

提交回复
热议问题