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
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,562 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  Need Help: FileNotFoundError:[Errno 2] No such file or directory python202209 5 2,633 Sep-12-2022, 04:50 AM
Last Post: python202209
  FileNotFoundError: [Errno 2] No such file or directory: 5l3y3r 6 8,107 Nov-02-2020, 12:48 PM
Last Post: 5l3y3r
  Shutil FileNotFoundError: Errno 2 Help lord_kaiser 8 10,511 Aug-10-2020, 08:45 AM
Last Post: lord_kaiser
  Getting FileNotFoundError: [Errno 2] ,if tries to acees same file from sub-directory pmpinaki 2 2,493 May-04-2020, 03:39 PM
Last Post: pmpinaki
  FileNotFoundError: [Errno 2] No such file or directory saqib1066 23 24,369 Mar-16-2020, 01:25 PM
Last Post: saqib1066
  [split] FileNotFoundError...System cannot find the path specified powerrocker 1 2,046 Oct-03-2019, 09:09 AM
Last Post: buran
Question pdfkit.from_string('Hello!','out.pdf') gives FileNotFoundError sipriusPT 3 9,319 Sep-19-2019, 01:44 PM
Last Post: snippsat
  FileNotFoundError: No such file or no access agatte 2 4,933 Sep-12-2019, 08:48 AM
Last Post: agatte
  FileNotFoundError...System cannot find the path specified alex9745 28 21,429 Jul-23-2019, 05:14 AM
Last Post: alex9745

Forum Jump:

User Panel Messages

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