Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
FileNotFoundError managment
#1
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?
Reply
#2
You could catch OSError instead of Exception, this will likely catch every file related exception. Note that OSError is a base type for FileNotFoundError.
Reply
#3
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need Help: FileNotFoundError:[Errno 2] No such file or directory python202209 5 6,187 Sep-12-2022, 04:50 AM
Last Post: python202209
  FileNotFoundError: [Errno 2] No such file or directory: 5l3y3r 6 10,551 Nov-02-2020, 12:48 PM
Last Post: 5l3y3r
  Shutil FileNotFoundError: Errno 2 Help lord_kaiser 8 14,154 Aug-10-2020, 08:45 AM
Last Post: lord_kaiser
  FileNotFoundError: [Errno 2] No such file or directory saqib1066 23 31,997 Mar-16-2020, 01:25 PM
Last Post: saqib1066
Question pdfkit.from_string('Hello!','out.pdf') gives FileNotFoundError sipriusPT 3 11,595 Sep-19-2019, 01:44 PM
Last Post: snippsat
  FileNotFoundError: No such file or no access agatte 2 5,898 Sep-12-2019, 08:48 AM
Last Post: agatte
  FileNotFoundError...System cannot find the path specified alex9745 28 26,727 Jul-23-2019, 05:14 AM
Last Post: alex9745
  FileNotFoundError when using subprocess dixitabhi 1 17,539 Mar-04-2018, 06:59 PM
Last Post: Larz60+
  where is FileNotFoundError at? Skaperen 4 15,486 Oct-03-2017, 01:49 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020