#include <exception>
#include <iostream>
#include <cstdio>
using namespace std;
class BaseException : exception {
public:
BaseException(const char* message) : message(message) {}
const char* getMessage() {
return message;
}
private:
const char* message;
};
void wrong() {
unsigned short int argumentCallCounter = 1;
/// @todo check why commented below does not work ?!
// char tmp[13 + sizeof(argumentCallCounter)];
/// @todo but this works
char* tmp = new char[13 + sizeof(argumentCallCounter)];
sprintf(tmp, "No %u argument", argumentCallCounter);
throw BaseException(tmp);
}
int main(int argc, char** argv) {
try {
wrong();
} catch (BaseException e) {
cout << e.getMessage() << endl;
}
return 0;
}
The code above works, but in comments, there is a code segment, that does not work.
char tmp[13 + sizeof(argumentCallCounter)];
I understand that it does not work because when the program leaves function wrong the variable tmp no longer exists.
Can anybody help with this?
And also that decision that I write:
char* tmp = new char[13 + sizeof(argumentCallCounter)];
It’s no good either, because when the program is complete, there is a memory leak, because nobody deletes tmp
It would not work because
tmpis local to the function, and it not more exists once you exit from the function, but you’re still trying to access it frommain().I would suggest you to use
std::stringinBaseExceptionand everywhere else.I would also suggest you to catch the exception by
constreference as:EDIT:
Implement
BaseExceptionas follows:Use it as:
EDIT:
And implement
wrong()as