# Exception while reading file

**URL:** <https://forum.juce.com/t/exception-while-reading-file/49929>\
**Category:** Getting Started\
**Created:** [January 31, 2022, 12:43pm UTC](https://forum.juce.com/t/exception-while-reading-file/49929 "2022-01-31T12:43:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![funtyper](https://avatars.discourse-cdn.com/v4/letter/f/3be4f8/32.png) [@funtyper](https://forum.juce.com/u/funtyper)\
**Post date:** [January 31, 2022, 12:43pm UTC](https://forum.juce.com/t/exception-while-reading-file/49929/1 "2022-01-31T12:43:35Z")

</div>

Hi,

While reading a file using the code shown below, I’m getting an exception (shown in the screenshot) that I am not able to catch. Can you please suggest what should I do?

```auto
File fileToRead = File::getCurrentWorkingDirectory().getChildFile("file.txt");
    if (!fileToRead.existsAsFile())
    {
        DBG("File doesn't exist ...");
    }
    
    std::unique_ptr<juce::FileInputStream> input{ fileToRead.createInputStream() };
    if (!input->openedOk())
    {
        DBG("Failed to open file");
        // ... Error handling here
    }

    bool readWholeFile = true;
    if (readWholeFile)
    {   
        try {
            String content = input->readString();
            // ... Do your stuff. New lines are normally seperated by "\n"
            DBG(content);
        }
        catch (const std::exception& e) {
        }
    }

```

 ![Exception](https://us1.discourse-cdn.com/flex026/uploads/juce/original/2X/1/1b764d98199a0fcd861b3d3fa313088a477eb78a.png)

---

<div class="post-metadata">

**Author:** ![reuk](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/reuk/32/21494_2.png) [@reuk](https://forum.juce.com/u/reuk)\
**Post date:** [January 31, 2022, 12:49pm UTC](https://forum.juce.com/t/exception-while-reading-file/49929/2 "2022-01-31T12:49:04Z")

</div>

Your program is crashing because it is dereferencing a null pointer. Perhaps `fileToRead.createInputStream()` is failing and returning a null stream. You should check `input != nullptr` before trying to call `input->openedOk()`.

---

<div class="post-metadata">

**Author:** ![funtyper](https://avatars.discourse-cdn.com/v4/letter/f/3be4f8/32.png) [@funtyper](https://forum.juce.com/u/funtyper)\
**Post date:** [January 31, 2022, 2:04pm UTC](https://forum.juce.com/t/exception-while-reading-file/49929/3 "2022-01-31T14:04:41Z")

</div>

Thank you @reuk , it worked 🎉
