I am trying to define a custom Exception class so that I can handle a specific type of error in my algorithm.
I'm using a bog-standard way of defining custom exceptions:
Inside MyCustomException.py:
class MyCustomError(Exception):
"""Custom exception"""
def __init__(self, msg):
super().__init__(msg)
Inside main.py:
import MyCustomException
try:
# two instruments for pairs trading
sym1, sym2 = pair_tuple
# handle the case when we can't find the symbol in question inside dictionary self.last_prices
try:
last_close1 = self.last_prices[sym1]
last_close2 = self.last_prices[sym2]
except KeyError:
# catch the KeyError and raise a specific error for handling.
raise MyCustomException.MyCustomError(f"{pair_tuple} not found")
# some other code....
except MyCustomException.MyCustomError as e:
# some error handling for this specific error
However, when I try this I keep getting the following error:
TypeError : catching classes that do not inherit from BaseException is not allowed
It looks like there's nothing wrong with my code - the exception class is inheriting from Exception which is confirmed when looking at MyCustomException.MyCustomError.__bases__. The one thing I think may be causing this is when I take a look at type(MyCustomException.MyCustomError), this returns "clr.clr MetaClass". Maybe this MetaClass is interfering with the logic in the except clause?
Aaron Janeiro Stone
Within python, there exists classes which cannot be passed into an exception (e.g., method objects and perhaps this clr MetaClass). See
https://stackoverflow.com/questions/53148112/python-3-handling-error-typeerror-catching-classes-that-do-not-inherit-from-bas
for details.
.ekz.
Any luck with this? I am contemplating using custom errors in a simar way.
BenjaminLee
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!