Python Forum
Looking for advice and Guidance on Exceptions used within Functions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Looking for advice and Guidance on Exceptions used within Functions (/thread-22462.html)



Looking for advice and Guidance on Exceptions used within Functions - paul41 - Nov-13-2019

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:

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


RE: Looking for advice and Guidance on Exceptions used within Functions - Larz60+ - Nov-14-2019

after last exception, add a raise statement to catch any other exceptions and terminate the program

I usually keep the the number of exceptions to one, that being the most likely to happen,
again, after the except, add a raise statement to catch any other exceptions