ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 31 Jan 2022 17:51:47 +0100Error Handlinghttps://ask.sagemath.org/question/60887/error-handling/I am very new to Sage, so apologies if the answer to this question is obvious.
I have a program, and at the final calculation, for T and E matrices calculated earlier, it needs to either calculate a matrix A such that `T=AE`, or, if this returns an error message, calculate a matrix A such that `p*T=AE`, where p is also calculated earlier.
In mock code, what I mean is:
Calculate E.solve_left(T)
If that returns an error:
A=E.solve_left(p*T)
else:
A=E.solve_left(T)
return A
But I don't know how to do that in real code.Sun, 30 Jan 2022 20:06:57 +0100https://ask.sagemath.org/question/60887/error-handling/Answer by Max Alekseyev for <p>I am very new to Sage, so apologies if the answer to this question is obvious.</p>
<p>I have a program, and at the final calculation, for T and E matrices calculated earlier, it needs to either calculate a matrix A such that <code>T=AE</code>, or, if this returns an error message, calculate a matrix A such that <code>p*T=AE</code>, where p is also calculated earlier.</p>
<p>In mock code, what I mean is:</p>
<pre><code>Calculate E.solve_left(T)
If that returns an error:
A=E.solve_left(p*T)
else:
A=E.solve_left(T)
return A
</code></pre>
<p>But I don't know how to do that in real code.</p>
https://ask.sagemath.org/question/60887/error-handling/?answer=60888#post-id-60888You need to handle an exception (this is Python feature inherited in Sage):
try:
A=E.solve_left(T)
except:
A=E.solve_left(p*T)Sun, 30 Jan 2022 20:16:03 +0100https://ask.sagemath.org/question/60887/error-handling/?answer=60888#post-id-60888Comment by Sébastien for <p>You need to handle an exception (this is Python feature inherited in Sage):</p>
<pre><code>try:
A=E.solve_left(T)
except:
A=E.solve_left(p*T)
</code></pre>
https://ask.sagemath.org/question/60887/error-handling/?comment=60898#post-id-60898Or simply:
try:
A = E.solve_left(T)
except:
A = E.solve_left(p*T)
Note that it is better to name the exception you expect to catch (for example `except ValueError`) to avoid catching unexpected errors.Mon, 31 Jan 2022 17:51:47 +0100https://ask.sagemath.org/question/60887/error-handling/?comment=60898#post-id-60898