I understand the basics on Exception handling. However, I am simply looking for the correct way of using the Exception handling when it comes to also using functions.
Say I have created a function named openFile will open a file:
[python]
def main():
file = 'openme.txt'
contents = openFile(filename)
print(contents)
[python]
Now say the filename does not exist and I hit the FilenotFoundError which is correctly handled and reported back. However, the code within the main continues and then attempts to print the contents.
Question 1: Should I have exception handling within a function like this? How can I get it to stop executing the rest of the code when it returns back to the main? If I add exit(1) to the exception like I have done above for the catch all other exception types this seems to work, but just wondering if this is the correct thing to do?
An alternative is I could add all of the exception handling within the main instead of having it within the function itself. However, this would make the main script very large when its fully completed.
I am really trying to understand where to use exception handling within functions or should they be used within your main part of the scripts.
Be grateful for any advice
Say I have created a function named openFile will open a file:
def openFile try: with open('myfile.txt') as fh: file_data = fh.read() print(file_data) except FileNotFoundError: print('The data file is missing') except PermissionError: print('There is a permission error') except Exception as err: print('Some other error has occurred:', str(err)) exit(1)Within my main I call this function but my main does something with the data for example:
[python]
def main():
file = 'openme.txt'
contents = openFile(filename)
print(contents)
[python]
Now say the filename does not exist and I hit the FilenotFoundError which is correctly handled and reported back. However, the code within the main continues and then attempts to print the contents.
Question 1: Should I have exception handling within a function like this? How can I get it to stop executing the rest of the code when it returns back to the main? If I add exit(1) to the exception like I have done above for the catch all other exception types this seems to work, but just wondering if this is the correct thing to do?
An alternative is I could add all of the exception handling within the main instead of having it within the function itself. However, this would make the main script very large when its fully completed.
I am really trying to understand where to use exception handling within functions or should they be used within your main part of the scripts.
Be grateful for any advice