I have a C++ class and I am trying to run it in Ubuntu:
#ifndef WRONGPARAMETEREXCEPTION_H_
#define WRONGPARAMETEREXCEPTION_H_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
#pragma once
class WrongParameterException: public exception
{
public:
WrongParameterException(char* message): exception(message) {};
virtual ~WrongParameterException() throw() {};
};
#endif
when I try to compile it, the compiler gives me this error:
WrongParameterException.h: In constructor ‘WrongParameterException::WrongParameterException(char*)’:
WrongParameterException.h:14: error: no matching function for call to ‘std::exception::exception(char*&)’
/usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()
/usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&)
Can anyone tell me what am I doing wrong? I tried changing the message variable to string or const string or const string& but it didn't help.
Here is how I use the new exception that I created from main:
try
{
if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL))
{
throw WrongParameterException("Error in the config or commands file");
}
}
catch(WrongParameterException e)
{
log.addMsg(e.what());
}
First, #pragma once is the wrong way to go about it, learn about header include guards. Related question on SO explains why using #pragma once is the wrong way to go about it. Wikipedia explains how to use include guards which serve the same purpose without any of the downsides.
Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array.
#include <stdexcept>
#include <string>
class WrongParameterException : public std::runtime_error {
public:
WrongParameterException(const std::string& message)
: std::runtime_error(message) { };
};
Would probably be what you want. For more information on exceptions, check out C++ FAQ Lite article on Exceptions and the exceptions article at cplusplus.com.
Good luck!
std::exception does not have a constructor that takes any kind of string, only a virtual what() method that returns the exception description.
You will have to store the string yourself and return it from there.
My advice would be:
Inherit from std::runtime_error. As advised by X-Istence above. It is conceptually a runtime error, and also the std::runtime_error constructor accepts a std::string as argument describing what happened.
About your catching the exception. I'd use catch(WrongParameterException const& e)
(note the const reference) instead of catch(WrongParameterException e), because first, the exception is normally constant in your case, and, also, using the reference, you catch any subclass of WrongParameterException in case your code evolves with some more refined exception handling.
std::exception's constructor doesn't take a string argument. You're trying to give it one, which is what causes the compile error.
You need to store your string, which would be better to handle as a std::string rather than a raw pointer, and return it from the what() method.
Looking at the declaration of the exception class in MS VS2K5, the constructor you want is:
exception (const char *const&);
so try changing your constructor to:
WrongParameterException (const char *const message)
and see if that helps. Otherwise, store the pointer in your own class and implement all the relevant methods.
A simple solution is to design your exception diferently. Here is a simple example:
class MyException : public Exception
{
public:
MyException(CString strError) { m_strError = strError; }
CString m_strError;
};
Then you can simply use your exception message as you please. This is because Exception does not have a contructor that excepts a String, so you have to stlre it on your own.
Related
I'm really struggling with throwing an error message that includes an argument from the function. I know I can do:
throw std::out_of_range("Empty tree");
What I am struggling with is another error I am supposed to throw, which is:
"Cannot find ceil for key <key>"
As you can see, I am supposed to include the key for which I cannot find the ceil for. I have the key as a variable in the function from which I am throwing the exception, but I have no idea how to include it in what will eventually be printed by e.what().
EDIT: This is a template function as a member of a class, so key is just type T right now. Hence why I think formatting it as a c string wasn't working.
The standard exceptions only take a string as an argument:
e.g. out_of_range, see apache.org docs
namespace std {
class out_of_range : public logic_error {
public:
explicit out_of_range(const string& what_arg);
};
}
You could use any method to build the string beforehand, and then pass that as the parameter to the exception.
Example:
#include <string>
#include <sstream>
#include <stdexcept>
std::ostringstream oss;
oss << "Cannot find ceil for key " << key;
std::string errorString = oss.str();
throw std::out_of_range(errorString);
For other ways to create the string, see C++ create string of text and variables
Are there any conventions about which error numbers I should use in my C++ code?
Do I start at 1 or should I pick a high number and go from there?
An example was requested, so here it is:
#define ERR_EVERYTHING_IS_WRONG 42
try
{
throw ERR_EVERYTHING_IS_WRONG;
}
catch(int err)
{
//
}
For try-catch, do not use numbers! Use a class derived from a standard exception class. Example:
#include <stdexcept>
class my_error : public std::runtime_error {
public:
explicit my_error(const std::string& what_arg) : std::runtime_error(what_arg) {};
};
Usage (Coliru):
#include <iostream>
int main() {
try {
throw my_error("You can even pass a string here!");
} catch (const my_error& e) {
std::cerr << e.what();
}
}
Or simpler: use std::runtime_error
#include <stdexcept>
#include <iostream>
int main() {
try {
throw std::runtime_error("Error happened");
} catch (const std::runtime_error& e) {
std::cerr << e.what();
}
}
Without standard library:
class my_error {
};
int main() {
try {
throw my_error();
} catch (const my_error& e) {
//TODO handle my_error
}
}
One of the best way is to follow standard for conventions of different errors in C++ codes is Enum
eg:
enum FILE_ERROR{
FILE_NOT_FOUND,
FILE_NO_ACCESS,
FILE_BUSY
};
so in code u can use FILE_NOT_FOUND as error number which is 0 . So this makes easy to understand what error type stands for what
There is no rule, you can do whatever you want as long as you keep a logical way to assign it.
If you choose 3 for bad user input, keep it for only that error or you'll get lost really soon
In C++ it is common to have 1 as success and 0 as error code, unlikely to C, where there are many functions returning 0 as success (strcmp, etc...)
this may be confusing sometimes, especially when interacting with C code, however I find that it helps a lot readability.
if(cplusplus_function()) {...}
is a lot more readable than
if(!c_function()){ ... }
remember also that you have exceptions to leverage in C++, and try to avoid nesting if-s
You don't "throw" any number, you "throw" an exception, an object of a class that derives from std::exception.
Standard exceptions contain text, and do not actually contain an error number. You can however create different classes for different types of exceptions, and have different catch handlers dependent on which exception type was thrown.
Our professor gave us a shell to make a program in. In it he gave us a class called "Maker", and it is capable of throwing exceptions. I'm confused about how to throw and catch the error, given the format of the constructor that he has provided.
He gave us his own special exception header file called CycleFoundException.h, which looks like this:
#include <iostream>
#include <exception>
using namespace std;
class CycleFoundException: public exception {
// Don't add code
};
Here is the Maker.h header file:
#include "CycleFoundException.h"
class Maker
{
private:
// insert instance variables
public:
Maker(int x) throw (CycleFoundException);
};
And finally the cpp shell, Maker.cpp:
#include Maker.h
Maker::Maker(int x) throw (CycleFoundException){
//add code here
}
int main()
{
return 0;
}
I've never seen a constructor declaration like this. Why is the "throw (CycleFoundException)" be tagged onto the declaration of the constructor? Is that necessary?
And how would I throw an exception given this format? Would I still do it the same way I would otherwise, aka if a certain condition is not met then throw the exception (from within the body of the constructor)? Thanks.
This is simply a way to say what kinds of exceptions a function is allowed to throw:
Maker::Maker(int x) throw (CycleFoundException)
means that Maker::Maker(int) is only allowed to throw CycleFoundException exceptions, nothing else. This is called an "exception specification."
Note that the C++ standard has deprecated this mechanism. It should not be used anymore. You should probably inform your professor about it ;-) They were always problematic: http://mu2e.fnal.gov/public/hep/computing/standards/C++FAQ.shtml#exceptionspec
I have read answers to following questions ->
c++ exception : throwing std::string
c++ Exception Class Design
My requirement is to catch exceptions and allow a mechanism to reformat the error messages and then re-throw the exceptions.
So I thought of writing my exception class which will provide a method to reformat the error message at various catch points.To make reformatting easy, I'm embedding a string object in myexception_base class.
I have also referred to this article -> http://www.boost.org/community/error_handling.html which clearly says not to embed string objects in exception classes.
The article also has a quote "Peter Dimov makes an excellent argument that the proper use of a what() string is to serve as a key into a table of error message formatters." but it does not elaborate on it any further.
I have written the code as given below and my questions are -
1) If I don't embed a string object in my exception class, it will make it difficult to reformat the what messages. Please tell me How shall I approach to my requirement without embedding a string object in my exception class?
2) If I carry on with my current approach of embedding a string object and providing a method to format error message. Is my way of handling some scenarios correct ? (Issue 1 and Issue 2 in which error msg doesn't get formatted)
Issue 1 - wrong exception getting propagated to catch points ?
Issue 2 - Error Message not getting formatted in some scenarios ?
Issue 1 and Issue 2 are mentioned in comments in code below.
Kindly have a look at the code. I have given lot of comments in code so lines of code has increased but if I remove the comments it has very less lines of code.
#include <string>
#include <exception>
#include <iostream>
using namespace std;
class myexception_base : public exception {
private:
string error_msg;
public:
myexception_base(const char* str) : error_msg(str) {
// std::string here here can throw an exception while error_msg
//initialisation through MIL.
// myexception_base object will not be constructed
// and wrong exception will be propagated to catch point(Issue 1)
}
const char* what() const throw() {
try {
return error_msg.c_str();
} catch (...) {}
// c_str can throw.
// I can't remove throw specification from what()
// because what() in base std::exception has throw() specification
// In case c_str() throws an exception program will terminate
// So to stop abnormal termination of program c_str
// is wrapped in a try catch block to ignore std::string exception
// program will not terminate but what message is not reformatted
// in such scenario (Issue 2)
}
void append_error_msg(const char* str) {
error_msg.append(str);
// append can throw
// Again error_msg will not be formatted (Issue 2)
}
~myexception_base() throw() {
}
};
void f();
void f2();
void f() {
throw myexception_base("Error Msg1");
}
void f2() {
//Some intermediate Catch point will reformat e.what() msg
//by appending an error msg2
try {
f();
}
catch (myexception_base& e) {
e.append_error_msg(": Error Msg2");
throw;
}
}
int main () {
try {
f2();
}
catch(const exception& e) {
// Finally the exception is caught in the upper most layer
// and proper error_msg is given to user
cout<<e.what()<<"\n";
}
}
According to the boost documentation embedding classes which might throw during their lifetime are not an excellent candidate to be used in the exception handler mechanism, so I would like to suggest that you will simply use the good old C way of handling strings. It will require some extra effort to bring it up and running but with them you have eliminated one source of error.
So, basically there are two approaches:
In the myexception_base you declare the error_msg as being an array of N chars. In the append_error_msg you carefully check that the length of the NEW string (after the append) is not greater than N and if it is not, then you use strcat or one of the other C string handling methods. This approach might be good, since it does not allow memory leaks through the exception handling mechanism, however you can have only a limited length of error message.
In the myexception_base you declare the error_msg as being a char* (a char pointer). In the constructor you callocmemory for it (do not use new since new might throw) and in the append_error_message you realloc the pointer to be the new size (ie. old size + string to be appended.size + 1 for the 0) and then memcpy to the requested position (ie. at the position of the end of the old string in the newly allocated string). Of course, do not forget to check all the allocations/re-allocations that they have returned a valid value otherwise you might get funny behavior. And last, but not least, to avoid the classical memory leaks, free the memory of the char* in the destructor.
Good luck!
I'm convinced at this point that I should be creating subclasses of std::exception for all my exception throwing needs. Now I'm looking at how to override the what method.
The situation that I'm facing, it would be really handy if the string what returns be dynamic. Some pieces of code parse an XML file for example, and adding a position or line number to the error message is useful to me.
I am trying to follow the Boost Exception handling guidelines.
What I'd like to know:
what returns a const char *, which implies any catcher is likely not going to free the string. So I need some other place to store the result, but where would that be? (I need thread-safety.)
what also includes throw() in its signature. While I can prevent my what from throwing anything, it seems to me that this method really isn't intended for anything too dynamic. If what is not the right place, then where should I be doing this instead?
From the answers I've gotten so far, it looks like the only way to accomplish this is by storing the string in the exception. The Boost guidelines recommend against this, which is confusing to me, because std::runtime_error does just that.
Even if I were to use a C-string, I'd have to use a statically sized buffer, or do memory management which can fail too. (I'm wondering if this is actually the only thing that can go wrong in std::string's copy-constructor. That would mean I won't gain anything using dynamically allocated C-strings.)
Is there any other option left?
My exception classes generally don't have anything but the constructor and look along these lines:
class MyEx: public std::runtime_error
{
public:
MyEx(const std::string& msg, int line):
std::runtime_error(msg + " on line " + boost::lexical_cast<string>(line))
{}
};
An arbitrary example, but it is the base class that handles managing the what() message.
But if you want to, you can also only assign the base part of the exception object, after you've put together the message in the constructor body.
#include <stdexcept>
#include <string>
#include <sstream>
class MyEx: public std::runtime_error
{
public:
MyEx(const std::string& msg, int line):
std::runtime_error("")
{
std::stringstream ss;
ss << msg << " on line " << line;
static_cast<std::runtime_error&>(*this) = std::runtime_error(ss.str());
}
};
#include <iostream>
int main()
{
try {
throw MyEx("Evil code", __LINE__);
}
catch (const std::exception& e) {
std::cout << e.what() << '\n';
}
}
However, regarding the boost's guidelines, perhaps you should pay attention to the point that numeric data (positions and lines) might best be made available as numbers through other methods. The guidelines say to worry less about the what() message.
Boost's guidelines appear to be based on two assumptions: copying the exception object might throw another exception, and the what() string isn't a robust or reliable tool. These are valid concerns if you're writing a library that will see wide use in a variety of environments. If you have better knowledge of how the exception will be used, you can judge if these concerns are justified or much ado about nothing. Programming is all about a series of tradeoffs, and the tradeoffs that make sense for the Boost developers might not apply to you.
Well, no problem, you can simply implement the constructor of your derived exception class to format the string you'll return from what(). Free the buffer you use for that in the destructor.
I'm accepting UncleBens' answer, because I consider it technically the most correct and complete answer to my original question.
For reference, I actually picked a different solution, and stopped using what altogether. I've refactored the code I have now to use something like this as the base exception class:
struct Exception : public virtual std::exception
{
virtual const char* what() const throw()
{
try {
return typeid(this).name();
}
catch (const std::exception& e) {
return "<unknown exception>";
}
}
// Extended description; may throw.
virtual void describe(std::ostream& out) const = 0;
};
Basically just filling what with the most meaningful thing I could find without bothering with it anywhere else. I'm going to see how this fares, I guess.