Raise exception vs. return None in functions?

后端 未结 5 1346
别跟我提以往
别跟我提以往 2020-12-22 20:49

What\'s better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the mos

5条回答
  •  甜味超标
    2020-12-22 21:26

    In general, I'd say an exception should be thrown if something catastrophic has occured that cannot be recovered from (i.e. your function deals with some internet resource that cannot be connected to), and you should return None if your function should really return something but nothing would be appropriate to return (i.e. "None" if your function tries to match a substring in a string for example).

提交回复
热议问题