擅长:python、mysql、java
<p>你至少有两个选择。</p>
<p>使用<code>return</code>语句:</p>
<pre><code>def do_something(parameter):
if parameter > 100:
# display error message if necessary
return # 'exit' function and return to caller
# rest of the code
</code></pre>
<p>您还可以<code>return soemthing</code>将<code>something</code>值传递回调用方。这可用于提供状态代码(例如0:成功,1:错误)。</p>
<p>或者更好的方法是<code>raise</code>例外:</p>
<pre><code>def do_something(parameter):
if parameter > 100:
raise ValueError('Parameter should...')
# rest of the code
try:
do_something(101)
except ValueError, e:
# display error message if necessary e.g. print str(e)
</code></pre>
<p>请参见Python手册中的<a href="http://docs.python.org/2/tutorial/errors.html" rel="noreferrer">exceptions</a>。</p>
<p>有内置的异常类(如上面的<code>ValueError</code>)。您也可以定义如下:</p>
<pre><code>class ParameterError(Exception):
pass
</code></pre>
<p>您还可以向自定义异常类添加其他代码以处理参数、显示自定义错误消息等。。。</p>
<p>列出了内置异常<a href="http://docs.python.org/2/library/exceptions.html?highlight=exception#exceptions" rel="noreferrer">here</a>。</p>