Python Newbie try except raise code bug

Hello,guys!I have got a hometask to create a code with try , raise, except. But something doesn`t work in mine. Could you, please, write what is wrong with the code ,so I would fix it? Thank you!!!

try:
filepath = ‘test_file.txt’
with open(filepath, ‘r’) as fio:
result = fio.readlines()
if not result:
raise Exception(“File is empty”)

except IOError as e:
result =
except Exception as e:
result =
print(e)

Python uses indentation for controlling the flow of the program.

try:
    filepath = ‘test_file.txt’
    with open(filepath, ‘r’) as fio:
        result = fio.readlines()
    if not result:
        raise Exception(“File is empty”)

except IOError as e:
    result = //something
except Exception as e:
    result = //something
print(e)

I’m not 100% sure that this will be correct, but if you haven’t included indentation, this would be the first step to solving your task.

2 Likes

Thank you!Identation is OK.With "if not "the code works. Do you know why it doesn`t with “else”? Just curious))

Where exactly would you put the else? It’s helpful if you show the code. If you mean to replace the if not result: with else not result: that won’t work because the else statement needs an if statement declared before it - it cannot stand alone, but is an optional addition to the if logic.

2 Likes

yes!You exactly got my point and I got yours!Thank you very much!

1 Like