0

I made some code to read a file and have a problem with try-catch block.

A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

Additional information: Could not find a part of the path 'D:...\WpfApplicationExample\bin\Debug\KeyWord\ROS\KeyWord_Booting_Time.json'.

I always meet this exception although already handled it. my directory does definitely not exist, but I already handle it by catch block, so why my app still crashes at this: StreamReader sr = new StreamReader(filePath).

Please take a look at the code below and tell me what is the problem?

        try
        {
            StreamReader sr = new StreamReader(filePath);
            jsonString = sr.ReadToEnd();
            sr.Close();
        }
        catch (System.IO.DirectoryNotFoundException e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }
        catch (System.IO.IOException e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }
        catch (Exception e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }
  • 4
    There is of course not point in catching 2 specific types of exceptions + a catch all exception if you are doing the same thing in each catch block! – jason.kaisersmith May 20 '20 at 05:12
  • 2
    Note the "first chance" language. Maybe you're debugging and have enabled first chance exceptions: https://stackoverflow.com/questions/564681/what-is-a-first-chance-exception – Simon Mourier May 20 '20 at 05:22
  • Are you sure that is it throws System.IO.DirectoryNotFoundException? I think, StreamReader throws System.IO.FileNotFoundException when filePath does not exists – Dilshod K May 20 '20 at 05:49
  • thank @Simon Mourier for your information, I understand now. – Trịnh Vũ Long May 20 '20 at 06:23
  • @TrịnhVũLong - If you found your solution, answer yourself to close the question and gain some points – Simon Mourier May 20 '20 at 06:33

1 Answers1

1

for anyone has same problem: refer below docs for understanding about first chance and second chance exceptions.

[https://learn.microsoft.com/en-us/archive/blogs/davidklinems/what-is-a-first-chance-exceptione]

my app is not really crash.. it just shows me a message to report me when an exception occurs.. if I click "continue" in message box.. it will keep running my app and land to catch block as expected.

FYI thank all.