1// Copyright (c) 2012 Robert Ramey
2//
3// Distributed under the Boost Software License, Version 1.0. (See
4// accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7// test custom exception
8
9#include <iostream>
10#include <functional>
11#include <boost/safe_numerics/safe_integer_range.hpp>
12#include <boost/safe_numerics/interval.hpp> // print variable range
13#include <boost/safe_numerics/native.hpp> // native promotion policy
14#include <boost/safe_numerics/exception.hpp> // safe_numerics_error
15#include <boost/safe_numerics/exception_policies.hpp>
16
17// log an exception condition but continue processing as though nothing has happened
18// this would emulate the behavior of an unsafe type.
19struct log_runtime_exception {
20 log_runtime_exception() = default;
21 void operator () (
22 const boost::safe_numerics::safe_numerics_error & e,
23 const char * message
24 ){
25 std::cout
26 << "Caught system_error with code "
27 << boost::safe_numerics::literal_string(e)
28 << " and message " << message << '\n';
29 }
30};
31
32// logging policy
33// log arithmetic errors but ignore them and continue to execute
34// implementation defined and undefined behavior is just executed
35// without logging.
36
37using logging_exception_policy = boost::safe_numerics::exception_policy<
38 log_runtime_exception, // arithmetic error
39 log_runtime_exception, // implementation defined behavior
40 log_runtime_exception, // undefined behavior
41 log_runtime_exception // uninitialized value
42>;
43
44template<unsigned int Min, unsigned int Max>
45using sur = boost::safe_numerics::safe_unsigned_range<
46 Min, // min value in range
47 Max, // max value in range
48 boost::safe_numerics::native, // promotion policy
49 logging_exception_policy // exception policy
50>;
51
52template<int Min, int Max>
53using ssr = boost::safe_numerics::safe_signed_range<
54 Min, // min value in range
55 Max, // max value in range
56 boost::safe_numerics::native, // promotion policy
57 logging_exception_policy // exception policy
58>;
59
60int main() {
61 const sur<1910, 2099> test0 = 7; // note logged exception - value undefined
62 std::cout << "test0 = " << test0 << '\n';
63 const ssr<1910, 2099> test1 = 7; // note logged exception - value undefined
64 std::cout << "test1 = " << test1 << '\n';
65 const sur<0, 2> test2 = 7; // note logged exception - value undefined
66 std::cout << "test2 = " << test2 << '\n';
67 const sur<1910, 2099> test3; // unitialized value
68 std::cout << "test3 = " << test3 << '\n';
69 sur<1910, 2099> test4 = 2000; // OK value
70 std::cout << "test4 = " << test4 << boost::safe_numerics::make_interval(test4) << '\n';
71 return 0;
72}
73

source code of boost/libs/safe_numerics/test/test_custom_exception.cpp