Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setter in exception class

Tags:

c++

What could be the implications of having a setter member function in an exception class? The motivation for having a setter is that sometimes there isn't enough data available at the point of throw in order to handle the exception properly at the point of catch; so the additional information has to be added when the stack is being unwound.

like image 954
Rup Avatar asked Nov 08 '10 16:11

Rup


People also ask

What is setter in OOP?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

Should setters throw exceptions?

Yes, throw the exception in the setter. If your code throws IllegalArgumentException at some later point in time, it would be confusing to the caller. From the docs: Thrown to indicate that a method has been passed an illegal or inappropriate argument.

What is the purpose of setter?

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.

Do encapsulation allows setters?

Advantage of Encapsulation in JavaBy providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.


1 Answers

Check out the Boost.Exception library and most precisely this page in the paragraph titled Adding of Arbitrary Data to Active Exception Objects:

void parse_file( char const * file_name )
{
    boost::shared_ptr<FILE> f = file_open(file_name,"rb");
    assert(f);
    try
    {
        char buf[1024];
        file_read( f.get(), buf, sizeof(buf) );
    }
    catch(boost::exception & e )
    {
        e << boost::errinfo_file_name(file_name);
        throw;
    }
}

Personally I find the technic pretty effective. Modify the exception (adding context) and rethrow.

Contrary to Java, in C++ you decide whether or not you include the stack frame when building your exception, so you don't incur the risk of losing it and it'll still refer to the point of the code that threw the first exception, while having significant context.

like image 83
Matthieu M. Avatar answered Sep 24 '22 22:09

Matthieu M.