0

I am new to "Try & Except" so sorry if my question is very novice. I tried to search the reason but didn't find any.

I am trying a very simple Try an Except for read_csv:

try:
  cntrl = pd.read_csv(my_directory + file, sep='|')
except FileNotFoundError:
  logger.critical("file not found")

logger.info(f"file imported. Number of records: {len(cntrl )}")

So, when I don't have the file, the try and except just prints the error and moves to next line of "logger.info" code to give the below error.

UnboundLocalError: local variable 'cntrl' referenced before assignment

Shouldn't the code stop when error is found and not move to next? When I run the read_csv code without try and except, it stops and throws the error as FileNotFound.

Deb
  • 499
  • 2
  • 15
  • Put your `logger.info` into `else`. Quote from [docs](https://docs.python.org/3/tutorial/errors.html#handling-exceptions): *"The [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) … [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) statement has an optional `else` clause, which, when present, must follow all except clauses."* – Olvin Roght May 28 '21 at 10:06
  • 1
    The entire concept of doing `try` and `except` is *NOT* to cause the program to crash when there is an error. After the `except` part, it continues. – Aryerez May 28 '21 at 10:15
  • in `except` you should `exit()` program to stop rest of code OR you should create empty `cntrl = pd.DataFrame()` to run rest of code – furas May 28 '21 at 11:12

1 Answers1

1

You can add some code that should run only if what's in the try statement doesn't raise an except state with else:

Besides that, if you want your code to stop if an error is raised, use sys.exit() inside the except statement:

However, as Aryerez stated, usually the point of the try-except statement is to prevent the code from crashing. If you want it to stop running if an error happens, you can just remove the try-catch statements altogether.

Felix L.
  • 222
  • 1
  • 11