I am thinking of ways to break this simple program I have made. I have a try-catch
block around a simple division statement, but I do not know if it is impossible to have an exception thrown in this case.
This is my Values.hpp
class that creates an object that has a value and an exception_ptr
. If an exception pointer is null for the object, then the object is valid.
#ifndef VALUES_HPP
#define VALUES_HPP
#include <exception>
template <typename T>
class Values
{
public:
Values(T t);
Values(std::exception_ptr e);
bool isValid() const;
T const& getValue() const;
private:
T val;
std::exception_ptr error;
};
template<typename T>
Values<T>::Values(T t) : val{ t }, error{nullptr}
{
}
template<typename T>
Values<T>::Values(std::exception_ptr e)
{
}
template<typename T>
inline bool Values<T>::isValid() const
{
return !error;
}
template<typename T>
inline T const & Values<T>::getValue() const
{
if (!error) return val;
std::rethrow_exception(error);
}
template <typename T0, typename T1>
Values<decltype(std::declval<T0>() / std::declval<T1>())> operator/(Values<T0> const& first, Values<T1> const& second)
{
if (!first.isValid()) return first;
if (!second.isValid()) return second;
try
{
auto answer = fiest.getValue() / second.getValue();
return answer;
}
catch (...) //Is this catch unreachable?
{
return std::current_exception();
}
}
#endif
Here is my main class that is using the Values objects and the division operator. It is in this class that I want to be able to change something to reach the catch statement.
#include “Values.h”
#include <string>
int main()
{
Values<int> first(10);
Values<int> second(10);
const auto answer = first / second;
Values<int> third(std::make_exception_ptr(std::string(“test1”)));
Values<int> fourth(10);
const auto answer2 = third / fourth;
}
Are there any ways to reach that catch statement? Or is it unreachable. I have not been able to find a way. Additional code added to the main class is allowed.