This may not be the best. The whole point of exceptions is that you can catch them at a completely different level than you raised. Itβs best to process them where you have enough information to do something useful with them (this is very dependent on the application and context).
For example, the code below may raise IOError ("[Errno 2] There is no such file or directory"):
def read_data(filename): return open(filename).read()
In this function, you do not have enough information to do something with it, but in the place where you actually use this function, in case of such an exception, you can try a different file name or show an error to the user or something else:
try: data = read_data('data-file.txt') except IOError: data = read_data('another-data-file.txt') # or show_error_message("Data file was not found.") # or something else
source share