-1

I have a function with following code:

if (!File::exists(i_filename)) throw new FileNotFoundException(i_filename);

My FileNotFoundException looks like this .h

#pragma once

#include <exception>
#include <string>

class FileNotFoundException : public std::exception {
public:
    FileNotFoundException(const std::string &i_filename);
private:
    std::string m_filename;
};

.cpp

#include "FileNotFoundException.h"

FileNotFoundException::FileNotFoundException(const std::string & i_filename) {
    m_filename = i_filename;
    // A message will be pushed to console & debug window, I first wanted to test
}

But Visual Studio tells me Unhandled Exception at 0x7432D8A8 in 2D Game.exe: Microsoft C++ Exception: FileNotFoundException at storage location 0x0018F5FC. when I run throw new FileNotFoundException(i_filename);

Does anyone know what's wrong? Sorry, but I have never created an exception class before.

1 Answers1

0

As the comments already showed, you need a try-catch block to catch the exception. Otherwise you won't be able to tell the compiler, what should happen, when the exception is thrown.

BTW it is a bad idea in C++ to throw pointers, because the type matching in the catch block might not be as expected. Throw a value instead and catch a reference to it:

if (!File::exists(i_filename))
    throw FileNotFountException{i_filename};

// .... somewhere else

try {
  // call the above function
} catch(FileNotFountException& e) {
  // handle the exception here
}

Besides your actual question: it is a good idea to prefer initialization lists over assigning values in the constructor:

class FileNotFountException : public std::exception {
    public:
        FileNotFountException(const std::string &i_filename): 
            m_filename{i_filename} {};
    private:
        std::string m_filename;
};

This will initialize m_filename with a copy of i_filename, while your implementation will initialize m_filename with an empty string and then copy the contents of i_filename.

If your constructor is simple, you should prefer to have the definition directly at the declaration in the header file. It will be compiled like an function declared inline.

cdonat
  • 2,748
  • 16
  • 24
  • Well, slowly but surely I understand how to use Exceptions.. And what to do in the catch block? You wrote "handle the exception here", but I would do all in the Exception class. –  Jan 22 '16 at 19:35
  • 1
    Nope, that is not a good place to do that. If an exception is never cought, the compiler might take some short cuts and rule out your assumptions. It might even strip of code to call the constructor of the exception class, when it can prove, that it will never be cought in any case. Just use them the way, they were meant to be used and you are safe from surprises. – cdonat Jan 22 '16 at 19:39
  • Okay thank you. I'll have a closer look at Exceptions. –  Jan 22 '16 at 19:44