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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With