Home > Net >  do not continue when exception
do not continue when exception

Time:06-22

I would like use "try except" statement, but in two function. I caught an exception in function, but function2 does anyway. How can i stop it until there is an exception

i want to transfer it to a window application. If the file does not load, I want to display an information window. I only want the program to go on (function2) when the file loads

class Files:
    def __init__(self):
        self.name = "fle.txt"
    def function(self):
        try:
            self.f = open(self.name, 'rb')
        except OSError:
            print("Problem!!!")
            
    def function2(self):
        print(self.f.read())
        
def main():
    file=Files()
    file.function()
    file.function2()

CodePudding user response:

Don't catch an exception unless you actually know how to handle it.

class Files:
    def __init__(self):
        self.name = "fle.txt"
        self.f = None
    def function(self):
        self.f = open(self.name, 'rb')
            
    def function2(self):
        if self.f is None:
            raise Exception("File not initialized!") #Example
            #return #just if you don't throw or exit
        print(self.f.read())

        
def main():
    file=Files()
    try:
        file.function()
    except OSError:
        print("Problem!!!")
    else:
        file.function2()

main()

CodePudding user response:

Wrap your function calls in a higher level try/except.

Of course, you would never write anything like this because it's so inflexible. This answer does not condone the OP's approach but suggests how that could be made to work.

class Files:
    def __init__(self):
        self.name = 'fle.txt'

    def function_1(self):
        self.fd = open(self.name)

    def function_2(self):
        print(self.fd.read())

    def __del__(self):
        try:
            self.fd.close()
        except Exception:
            pass


file = Files()

try:
    file.function_1()
    file.function_2()
except Exception as e:
    print(e)

So we don't do any exception handling (except in __del__ where we ignore any issues) within the class functions but allow all/any exceptions to propagate to the caller. Here we want to call two class functions but we wrap them in the same try/except block.

If function_1 raises an exception, function_2 won't be called.

del added to show how one could clean up but it's not the way this should be handled

CodePudding user response:

@tomgalpin is right you could just exit right there after the problem But this being a class maybe you want to print the error and pass back no data?

Here's one way to look at that with Tom's included sys exit (commented out)

Also be sure if you keep your code to close the file handler. Calling open on a file without .close() can leave file handlers open and cause problems for you if your class were to continue on after.

class Files:
    def __init__(self):
        self.name = "fle.txt"
        # Empty string in data if no data
        self.data = ""
    def function(self):
        try:
            #self.f = open(self.name, 'rb')
            with open(self.name, 'rb') as f:
                self.data = f.read()

        except OSError as err:
            print("Problem!!!", err)
            # You could exit
            # sys.exit()
        # But you could also return an empty string, 
        #  which is "falsy", regardless of what happens
        finally:
            return self.data
            
    def function2(self):
        print(f"Data 3 {self.data}")
        
def main():
    file=Files()
    # You could print this, or use it to get the data
    print("Data 1", file.function())
    data = file.function()
    print(f"Data 2 {data}")
    # this now also shows the data
    file.function2()

CodePudding user response:

Use the variable that is usually True but becomes False if function fails

Example

class Files:
    def __init__(self):
        self.name = "fle.txt"
        self.continue=True
        self.data = ""
    def function(self):
        try:
            #self.f = open(self.name, 'rb')
            with open(self.name, 'rb') as f:
                self.data = f.read()

        except OSError as err:
            print("Problem!!!", err)
            self.continue=False
            return False
        finally:
            return self.data
            
    def function2(self):
        if self.continue:
            print(self.data)
        else:
            #Code if function failed
        
def main():
    file=Files()
    file.function()
    file.function2()
  • Related