Hi all,
Sorry in advance if that is a rookie python question... I am trying to improve my error handling to prevent run time errors from stopping my algo in live / Alpha Streams, while still logging informative messages in case errors are encountered.
I have tried different syntaxes:
Syntax 1
try:
...
except ValueError:
self.Log("Some hardcoded message mentioning a ValueError")
Syntax 2
try:
...
except:
self.Log("Some hardcoded message")
Syntax 3
try:
...
except Exception as ex:
self.Log("An exception of type " + str(type(ex).__name__) + " occurred. Arguments: " + str(ex.args) )
I have found that syntax 3 does not work, i.e. in that case the ValueError still triggers a run time error, stopping the execution of the algo.
Syntax 1 and syntax 2 are effective, in the sense that the error no longer stops the algo. However they are not ideal because:
- For various reasons, it is impractical or even impossible for me to predict all the types of errors that may be encountered (I cannot be sure they will be only ValueError)
- On the other hand, catching all exceptions without extracting information about the error is not informative enough (and firmly against good coding practices it seems)
Any advice would be greatly appreciated
Thanks in advance
Jack Simonson
Hey Pierre,
The python sys and traceback modules offer some help. If you use a regular try/except without raising an exception, you can fetch the exception information using sys.exc_info(), which will return the exception type, value, and other information. I've attached a backtest that shows how to log the exception information in detail while allowing your algorithm to continue to run. There's some good documentation here if you want to play around with how to display the errors. I hope this helps!
Pierre Vidal
Hi Jack,
Great, exactly what I needed.
I will be using that method going forward.
Thanks a lot for your patience in sharing basic Python tricks!
Pierre Vidal
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!