Raise an error and after that return a value in Python
<p>I want to raise an error and then return a value.</p>

<pre><code>raise ValueError('Max Iter Reached')
return x
</code></pre>

<p>And make both lines work.</p>

<p>Now I found this question is stupid and I decided to print an error message.</p>

<pre><code>print 'Max Iter Reached'
return x
</code></pre>

<p>This is impossible.  A function can <em>either</em> return a value <em>or</em> raise an exception.  It <em>cannot</em> do both.  Calling <code>return</code> or <code>raise</code> will absolutely terminate the function.</p>

<p>You could encode a return value inside the exception message, like this:</p>

<pre><code>raise SomeException('my value is 5')
</code></pre>

<p>Or you could return a tuple of an exception <em>and</em> a value:</p>

<pre><code>return (SomeException('hello'), 5)
</code></pre>

python