Answer the question
In order to leave comments, you need to log in
Is it necessary to use custom exception classes?
Please tell me, is it necessary to use my own exception classes in my code? In general, it is good practice to create classes of exceptions and catch them specifically, and not just faceless Exceptions. But I have doubts about the fact that in the code below they will not be of particular use, but the complexity and readability of the code will suffer significantly
class Main:
def __init__(self, config, credentials, Parser, DB_connection, Sql_requester):
self.config = config
self.parser = Parser(self.config)
self.db_connection = DB_connection(credentials)
self.sql_requester = Sql_requester
self.content = []
try:
self.get_content()
self.save_content()
except Exception as e:
# write to logger
print('stop program::', e)
def get_content(self):
self.content = self.parser.get_content()
def save_content(self):
with self.db_connection as db_connection:
# some code
if __name__ == '__main__':
Main(config, credentials, Parser, DB_connection, Sql_requester)
class Parser:
def get_content(self):
try:
root_html = self.get_html(self.config.url)
links = self.get_links(root_html)
content = self.get_content_inner(links)
return content
except Exception as e:
# write to logger
raise Exception('geting content for parse is failed ')
def get_html(self, url):
try:
# some code
except Exception as e:
# write to logger
raise Exception('getting html of ' + url + ' is failed',)
def get_links(self, html):
try:
# some code
except:
# write to logger
raise Exception('getting links to inner pages is failed')
def get_content_inner(self, links):
try:
# some code
except:
# write to logger
raise Exception('parse of inner page is failed')
try:
# some code
except:
# write to logger
raise Exception('formating data of inner page is failed')
Answer the question
In order to leave comments, you need to log in
It's good practice to catch as specific exceptions as possible, not Exception. And from this it follows that using your own exception classes is also good.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question