I would like to convert this code to use exceptions (let's assume that in practice, this code would be more complex.). The question is, how/where would I do it? Do I catch the exception in the constructor, main(), or in one of the other functions? Where do I define the exception class? Would it be part of CTest, or another file altogether? Basically, I'd like to catch exceptions and exit execution cleanly - allowing any cleanup to be done. Any words of wisdom?
Class definition:
Code:
//File: Test.h
#include <string>
#include <iostream>
using namespace std;
class CTest
{
public:
string m_Welcome;
CTest(string str_welcome);
void SetWelcomeString(string welcome_str);
int DoSomething(void);
};
Class implementation:
Code:
//File: Test.cpp
#include "Test.h"
CTest::CTest(string welcome_str)
{
CTest::SetWelcomeString(welcome_str);
if(CTest::DoSomething())
{
cerr << "Error!" << endl;
exit(1);
}
}
void CTest::SetWelcomeString(string welcome_str)
{
m_Welcome = welcome_str;
}
int CTest::DoSomething(void)
{
//returns 0 on success, 1 on failure
if(m_Welcome.length())
{
cout << m_Welcome << endl;
return(0);
}
//else
return(1);
}
Main:
Code:
//File: ExceptTest.cpp
#include "Test.h"
int main()
{
CTest testing("Hello, World!");
return 0;
}