Python Forum

Full Version: FileNotFoundError managment
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have a question about exception management
With the following code:
try:
    try:
       with open('foo.json') as json_data_file:
          pass
    except FileNotFoundError as e:
       print (f"f1: {e.filename}")
       raise
except Exception as ex:
    print (f"f2: {ex.filename}")
    ex2 = FileNotFoundError(ex)
    print (f"f3: {ex2.filename}")
I get the following output:
Output:
f1: foo.json f2: foo.json f3: None
With "ex.filename" get a pylint warning about "Instance of 'Excepetion' has no 'filename' member".
Usually in other language I do a cast, I tried it but I get "None" value.

Can I read filename from generic exception?
You could catch OSError instead of Exception, this will likely catch every file related exception. Note that OSError is a base type for FileNotFoundError.
(Oct-22-2019, 04:36 PM)Gribouillis Wrote: [ -> ]You could catch OSError instead of Exception, this will likely catch every file related exception. Note that OSError is a base type for FileNotFoundError.

thanks!