Question

Obviously something goes wrong with my understanding of this topic, but I can't find out where. The thing I want to implement is a custom Exception called CustomException. What I have made does compile and can work, but I do think that I am making use of header files the wrong way. So I have made the following 3 files:

  1. main.cpp

    #include "exception.h"
    
    int main() {
        try {
            throw CustomException();
        } catch (CustomException ce) {
            ce.doSomething();
        }
    }
    
  2. exception.h

    #include <exception>
    
    class CustomException : public std::exception {
        private:
            char* msg;
        public:
            CustomException() {};
            void doSomething() {};
    };
    
  3. exception.cpp

    #include "exception.h"
    
    CustomException::CustomException() {
    }
    
    void CustomException::doSomething() {
        printf("Hello World!");
    }
    

After I run this is the command line:

$ g++ main.cpp -o main.o
$ ./main.o
$

But the behaviour that I was looking for is, that "Hello World!" is printed to the command line. I am more used to JAVA, so maybe that is why I have a rough start with C++. Anyways I hope you can help me, because the tutorials I found differ from each other and don't make sense to me.

Was it helpful?

Solution

Your problem is that you're defining CustomException::doSomething() to do nothing: {}. Leave out the {} method definitions in exception.h. Then compile and link exception.cpp into your binary:

$ g++ -c main.cpp -o main.o
$ g++ -c exception.cpp -o exception.o
$ g++ main.o exception.o -o main
$ ./main

Note that a ".o" suffix is normally used for object files, not for executables.

OTHER TIPS

In addition to what user3553031 said, there is another posslble problem with your code. In C++ you should catch exceptions by reference, not by value. Otherwise it can cause problems. See this: C++ catch blocks - catch exception by value or reference?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top