Medvednic
Medvednic

Reputation: 692

Custom exception class - weird behavior

I've created a custom exception class testException.

throw creates a testException object which upon creation receives the desired name of the exception.

When a testException is caught (by reference) it should return the name of the exception by using the member function Get.Exception.

For some reason the function isn't called and instead I get the error:

terminate called after throwing an instance of testException

I saw a similar example here, which supposedly should work.


Code:

Exception.h

#include <iostream>
#include <string>
#ifndef TESTEXCEPTION_H
#define TESTEXCEPTION_H

using std::cout;
using std::cin;
using std::endl;
using std::string;

class testException {
public:
    testException(string);
    string GetException();
    ~testException();
protected:
private:
    string myexception;
};

#endif // TESTEXCEPTION_H

Exception.cpp

#include "testException.h"

testException::testException(string temp) : myexception(temp) {
    // ctor
}

string testException::GetException() {
    return myexception;
}

testException::~testException() {
    // dtor
}

main.h

#include <iostream>
#include "testException.h"

using std::cout;
using std::cin;
using std::endl;

int main() {
    throw testException ("Test");
    try {
        // Shouldn't be printed if exception is caught:
        cout << "Hello World" << endl;
    } catch (testException& first) {
        std::cerr << first.GetException();
    }
    return 0;
}

Upvotes: 0

Views: 81

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

You are throwing the exception outside of the try block.

int main() {
    throw testException("Test"); // Thrown in main function scope.
                                  // Will result in call to terminate.
    try {
        /* ... */
    } catch (testException& first) {
        // Only catches exceptions thrown in associated 'try' block.
        std::cerr << first.GetException();
    }
    /* ... */
}

An exception can only be caught when thrown inside of a try-catch clause. Throwing an exception in the main function scope will result in a call to terminate.

A try block will "try" to execute everything inside and if any exceptions are thrown along the way, they will be caught if the the associated exception handler takes a parameter with a type that the thrown exception is implicitly convertible to.

Once an exception is thrown the rest of the remaining statements inside of the try block will be skipped, all objects with automatic storage duration will be destroyed and the exception will be handled accordingly.

Live example with throw statement moved inside try-catch clause

Upvotes: 3

Edward
Edward

Reputation: 304

move throwing line: throw testException ("Test"); into try {} catch(catch (testException& first) {} block.

Upvotes: 2

Related Questions