Which of the following two methods of raising an error is preferred?
def _fetch_data(self):
if self.from_cache:
logger.debug('Trying to load local file %s...' % self.fp)
# Grab the data from a local file
if not os.path.exists(self.fp):
# first way -- from logger
logger.error('ERROR: Local file {self.fp} does not exist')
# second way -- directly raising
raise SystemExit(f"ERROR: Local file {self.fp} does not exist")
Why is one approach preferred over the other?
One of them prints and takes no action (implying the issue is non-fatal), the other actually attempts to terminate the program (though the idiomatic approach in this case would just be sys.exit(f"ERROR: Local file {self.fp} does not exist")
; it's equivalent to the raise
, but slightly clearer in intent).
Choose the one that makes sense in context; if the file is necessary to continue operation, raise an exception (log first if you like), if it's non-fatal with a reasonable way of continuing operation, you can just log.
Note that SystemExit
implies it's really fatal (people shouldn't be trying to catch that typically). Often, it's better to raise some other, more descriptive, less "implies definitely fatal" exception in case the caller knows a good way to handle the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.