summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBoris Kolpackov <boris@codesynthesis.com>2018-05-04 16:14:03 +0200
committerBoris Kolpackov <boris@codesynthesis.com>2018-05-04 16:14:03 +0200
commitb636924958794af6763c7098ea7d36f73c8b7f44 (patch)
tree3066b86a7a98e959f343e5b9777a5fb135dd8ab6
parent8728018f93a73b08a68ab1cea502a5f6b4a2a79e (diff)
Improve libhello with better error handling
-rw-r--r--libformat/libformat/format.cxx11
-rw-r--r--libformat/libformat/format.hxx4
-rw-r--r--libformat/tests/basics/driver.cxx27
3 files changed, 38 insertions, 4 deletions
diff --git a/libformat/libformat/format.cxx b/libformat/libformat/format.cxx
index de8a782..6450093 100644
--- a/libformat/libformat/format.cxx
+++ b/libformat/libformat/format.cxx
@@ -2,6 +2,7 @@
#include <cctype> // to{upper,lower}()
#include <algorithm> // transform()
+#include <stdexcept>
using namespace std;
@@ -10,9 +11,13 @@ namespace format
string
format_hello (const string& g, const string& n, volume v)
{
- string r (g);
+ if (const char* w = (g.empty () ? "empty greeting" :
+ n.empty () ? "empty name" : nullptr))
+ throw invalid_argument (w);
- transform (r.begin (), r.end (), r.begin (),
+ string h (g);
+
+ transform (h.begin (), h.end (), h.begin (),
[v] (char c) -> char
{
switch (v)
@@ -24,6 +29,6 @@ namespace format
return c;
});
- return r += ", " + n + '!';
+ return h += ", " + n + '!';
}
}
diff --git a/libformat/libformat/format.hxx b/libformat/libformat/format.hxx
index 3641b67..489f63c 100644
--- a/libformat/libformat/format.hxx
+++ b/libformat/libformat/format.hxx
@@ -9,5 +9,7 @@ namespace format
enum class volume {quiet, normal, loud};
LIBFORMAT_SYMEXPORT std::string
- format_hello (const std::string& greeting, const std::string& name, volume);
+ format_hello (const std::string& greeting,
+ const std::string& name,
+ volume = volume::normal);
}
diff --git a/libformat/tests/basics/driver.cxx b/libformat/tests/basics/driver.cxx
index 03faea7..dbc9358 100644
--- a/libformat/tests/basics/driver.cxx
+++ b/libformat/tests/basics/driver.cxx
@@ -1,4 +1,5 @@
#include <cassert>
+#include <stdexcept>
#include <libformat/version.hxx>
#include <libformat/format.hxx>
@@ -8,7 +9,33 @@ using namespace format;
int main ()
{
+ // Basics.
+ //
assert (format_hello ("Hello", "World", volume::quiet) == "hello, World!");
assert (format_hello ("Hello", "World", volume::normal) == "Hello, World!");
assert (format_hello ("Hello", "World", volume::loud) == "HELLO, World!");
+
+ // Empty greeting.
+ //
+ try
+ {
+ format_hello ("", "World");
+ assert (false);
+ }
+ catch (const invalid_argument& e)
+ {
+ assert (e.what () == string ("empty greeting"));
+ }
+
+ // Empty name.
+ //
+ try
+ {
+ format_hello ("Hello", "");
+ assert (false);
+ }
+ catch (const invalid_argument& e)
+ {
+ assert (e.what () == string ("empty name"));
+ }
}