How to 'ignore' an error in Python?
Cameron Simpson
cs at cskk.id.au
Fri Apr 28 21:36:07 EDT 2023
On 28Apr2023 16:55, Chris Green <cl at isbd.net> wrote:
> for dirname in listofdirs:
> try:
> os.mkdir(dirname)
> except FileExistsError:
> # so what can I do here that says 'carry on regardless'
> except:
> # handle any other error, which is really an error
>
> # I want code here to execute whether or not dirname exists
>
>Do I really have to use a finally: block? It feels rather clumsy.
You don't. Provided the "handle any other error" part reraises or does a
break/continue, so as to skip the bottom of the loop body.
ok = true
for dirname in listofdirs:
try:
os.mkdir(dirname)
except FileExistsError:
pass
except Exception as e:
warning("mkdir(%r): %s", dirname, e)
ok = False
continue
rest of the loop body ...
if not ok:
... not all directories made ...
2 notes on the above:
- catching Exception, not a bare except (which catches a rather broader
suit of things)
- reporting the other exception
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list