Python error handle

Hi there-- Am I missing here ?. This is in my second cell. My program has six steps.
I want to exit out when there is no data/filename. Attached is the screenshot of same.
Any hints appreciated…thanks

-------below is my code------------------------------

from ayx import Alteryx
import sys
try:
df=Alteryx.read("#1")

except:
sys.exit()

1 Like

Get rid of that “try:… except: sys.exit()” so you can see what the
actual error is.

1 Like

I still get the unable to read data error, when no file is present.

1 Like

To be fair, shouldn’t you expect that behaviour?

This means that you should be catching an exception. Just not any
exception. The rule of thumb is that you should catch only what you
expect - other exceptions are “exceptional”, and you want them to get
out so that you can debug their cause.

So put back a try/except in your code, but be much more specific:

from logging import warning
import sys
try:
    df = Alteryx.read("#1")
except FileNotFOundError as e:
    warning("missing file: %s", e)
    sys.exit(1)

There’s quite a range of quite specific exceptions: Built-in Exceptions — Python 3.9.6 documentation

The idea is that you should only handle expected situations. Unexpected
stuff need to make noise, otherwise your programme silently proceeds,
usually making nonsense of some kind.

Finally, sys.exit() is ok in a main programme (outside all functions).
Inside a function your almost never want to do that; instead you would
either raise an exception (which you could do by just not catching it)
or returning a special value indicating failure. If the above were in a
function you might return None if you chose that course - naturally
whataver called the function should know what to do with such a thing,
which is why an exception is often a preferred source of action.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Note: you’ll have to fix the typo above - Python is case sensitive and I
mistyped the case above.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Well of course you can’t read the file if the file doesn’t exist!

You have to decide what you want to do when the file doesn’t exist.
Explain to us in words what you want to do, and then try to write code
to do it.

1 Like

Thanks @cameron I did try your snippet. It seems to have done something.
But looks like cell below the 2nd cell still need some tweaks…thank you

1 Like

Well figuring that out is part of the fun.

If you get stuck and come back with a question, remember to include the
current code and a full transcription of any exception or output.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like