0

I'm writing a code that uses files. I want to check if the name of the files are empty string, and if so to raise a ValueError. Moreover, I want to close all the files, no matter what

  1. Can I raise a ValueError before the "try" block of the code?
  2. Is it OK to write the code only with "try" and "finally"?

    `def functio(file_1, file_2):

    if file_1 == '' or file_2 == '':
            raise ValueError("Invalid input")
    try:
       ~rest of the code~
    
    finally:
       if file_1 =! None or file_2 != None:
         file_1.close()
         file_2.close()`
    

2 Answers2

1

Python has something called 'context managers' which help you with what you're trying to do.

def function(file_1, file_2):
    if file_1 == '' or file_2 == '':
        raise ValueError("Invalid input")

    with open(file_1) as f1, open(file_2) as f2:
        ... # here goes the code that handles the files

Files will be opened at the start of the with block and will be closed appropriately when exiting the block.

Can I raise a ValueError before the "try" block of the code?

Yes, you can. However, it will abort the execution of the program if there's no except block to catch it.

Is it OK to write the code only with "try" and "finally"?

Yes, you can. But it's more correct to use context managers for this, as I described above.

jxpp
  • 163
  • 6
0
  1. You can, but the exception will be raised and the code will stop.
  2. You can do that, but if there is an error in the try portion, the code will stop if you don't have a except:. However it will execute the finally: part before stopping.
Axel Puig
  • 1,304
  • 9
  • 19
  • 1. good, that's what I wanted. So is there any difference between raising this in the try block or before? – user9946249 Dec 05 '18 at 22:17
  • If you raise the exception in the try block, the code in the `finally:` part will be executed. Else it will not. – Axel Puig Dec 05 '18 at 22:18
  • Not sure I understood. If I wrote it before the try, it means it won't get to the finally part? – user9946249 Dec 05 '18 at 22:25
  • Yes, like any other exception, it stops the code. If you want to run the `finally` part, the exception must be raised in the `try` part. (That's the role of `try`: doing something specific if an exception is raised.) – Axel Puig Dec 05 '18 at 22:35
  • @Alex Pluig I see it now. In my code, I opend the files in the `try` part, therefore if the strings are empty it won't open them anyway (I checked it before the `try` part), so I guess it doesn't matter if it gets to the `finally` part – user9946249 Dec 06 '18 at 06:48