Home > Software engineering >  How to raise exceptions for when file is not specified and when the specified file does not exists?p
How to raise exceptions for when file is not specified and when the specified file does not exists?p

Time:05-15

I a script I have:

if __name__ == '__main__':
  try:
    file = sys.argv[1]

    with open (file, 'rb') as img_file:

I run the script in terminal as:

python3 script.py file

I want to account for 2 cases where the specified file does not exist and the script prints "file does not exists" and also when the file is not being specified by the user (python3 script.py) and the script prints "file not specified". How should these 2 exceptions be included in the script?

CodePudding user response:

import sys

try:
  file = sys.argv[1]
  with open(file, 'rb') as img_file:
    pass
except IndexError:
  print("file not specified")
  raise
except FileNotFoundError:
  print("file doesn't exist")
  raise

CodePudding user response:

I recommend validate before logic directly, not catch the exception with the hole block.

import os
import sys

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('file not specified')
        sys.exit(1)
    
    file = sys.argv[1]
    if not os.path.exists(file):
        print('file {} does not exists'.format(file))
        sys.exit(1)
    if not os.path.isfile(file):
        print('{} is not a file'.format(file))
        sys.exit(1)
    with open (file, 'rb') as img_file:
        # TODO: your logic here
        pass
  • Related