14

I want to build a class with functions that may throw exceptions that I want to catch when I use it. I inherit my_exception from the standard exception class. I implement the what() function so that it returns a string that is stored in a private string variable

I think it would be better to define the exception as a nested class, the way it's done in iostream library with ios_base::failure.

What I'm less sure about, is where and how I should define the object of my_excpetion. I wish I could see the inner code of the iostream functions and see how they did it. I have thought about several options:

  1. For each reason of exception I can define a static instance of my_exception, with a constructor that gets a string and save it to my private string pointer.

  2. For each reason of exception I can define another class that inherit from my_exception and implement what as a function that returns a constant string (the reason). I can hold an instance of each of that exceptions sub-classes, or to throw the type. BTW, when do we usually throw type and not instance?

  3. I guess it's wrong: each time I want to throw an exception, to create a new my_exception with a constructor that gets a string. This is done in Java, but as I understand it will be problematic in C++ because the exception should be deleted somewhere. Right?

I think that the 1st one is the right one, is it? Are there more standard options?

Thank you very much!

1
  • nice question, but very subjective. Commented May 28, 2011 at 4:49

3 Answers 3

21

Short answer: You are going to want to throw the exceptions as objects, rather than as pointers. You will catch them as references.

Longer answer: all of the options you list are valid. In general, the reason you are going to want to throw an object, rather than a pointer, is becuase of the choices you give yourself and your clients when the exception is caught.

If you catch by pointer, catch (my_exception* e) then you don't know from looking at it whether you should delete the memory or not.

If you catch by value, catch (my_exception e) then you have a risk of slicing, if the exception object ends up being a base class with some other derived classes.

Catching by reference has neither of these problems. If you write catch (my_exception& r) then you can catch polymorphic objects, and you don't have to worry about releasing the memory.

So, to answer your other question, when you throw, just throw a temporary object: throw my_exception(). This creates a temporary object that is (probably) copied when thrown, caught by reference, and destroyed automatically when it goes out of scope at the end of your catch block. (This is actually another benefit of catch-by-reference over catch-by-value, since catch-by-value creates yet another copy when it's caught.)

As for your other, derived exception classes, it's a style choice. Deriving from my_exception with a different what() implementation is pretty standard. I wouldn't say you need to get fancy with storing the strings or instances in static objects - they're small, and constructing one is going to take practically no time compared to the process of unwinding the stack when the exception is thrown.

Sign up to request clarification or add additional context in comments.

5 Comments

It won't be copied if you catch it by reference, as you recommend.
note that unless you plan on modifying the exception (adding context and rethrowing), then you should catch it by const reference.
@ildjarn Good point. I'll clarify that. Isn't it the case though that, absent compiler optimization, the original temporary that you create gets copied and destroyed, and that it's that copy that is actually caught by reference?
@Matthieu M. That's interesting, I haven't heard that recommendation before. What is the advantage of doing it that way? When you declare a function parameter as const &, you gain the advantage of being able to bind to r-values, and you assure the caller that you won't be modifying the object that's passed in, but those advantages don't apply in a catch block. A (admittedly purely theoretical) disadvantage would be an inability to call any non-const members on some arbitrary thrown object.
Actually, not being able to modify the object does apply :) It tells the reader you won't change the exception reason, nor add any context. I am must admit I only recently realized this possibility myself, so my code base is a mismatch of ex& and ex const& catch blocks, but I do find the latter a better practice. I am a bit of const-addict though ;)
13

If you derive from std::runtime_error you do not need to define your own member to store the string. This is done for you in the std::exception (the base of std::runtime_error). It is not defined how the exception stores the string but it it should always work.

#include <stdexcept>
#include <string>

struct MyException: public std::runtime_error
{
    MyException(std::string const& message)
        : std::runtime_error(message + " Was thrown")
    {}
};

4 Comments

+1 for the idea, but to be pedantic std::exception has no constructor for strings or storage, but std::runtime_error does. (MSVC supports it in std::exception anyway, though.)
@GMan: Absolutely correct. That's why I use std::runtime_error
Ok, I was just confused about this part: "you do not need to define your own member to store the string. This is done for you in the std::exception"; that's not (necessarily) true.
@GMan: Technically true. Its not defined by the standard where the message is stored for any of the types derived from std::exception and thus each type could use its own method to store the physical message. All we know for sure on std::runtime_error: Postcondition (of the constructor with a single std::string argument what_arg: strcmp(what(), what_arg.c_str()) == 0.
0

Nothing wrong with any of your options. Number 3 is OK, as long as you make a local variable and not use new, because there's no need to delete the exception object - it will be destroyed as soon as you throw. You will need to make a copy constructor and copy operator, because the thrown exception will actually be a copy of the one you give to the throw statement.

Option 1 would be unusual because it's not normally necessary.

For option 2 you would create an instance of the class to throw. It's not possible to throw a type, only an instance of a type.

1 Comment

Thanks for the remark for the general case. Although in my simple case, I think that the default copy constructor would work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.