From 51ea36e444078015bb814b80aeeb2b80759292e6 Mon Sep 17 00:00:00 2001 From: jbeder Date: Thu, 1 Jan 2009 02:40:18 +0000 Subject: [PATCH] Added a templated derived exception to KeyNotFound so that you can figure out *which* key wasn't found. --- include/exceptions.h | 14 ++++++++++++++ include/node.h | 2 +- yaml-reader/main.cpp | 12 +++++++----- yaml-reader/tests/test.yaml | 10 +++------- 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/include/exceptions.h b/include/exceptions.h index 5dc0062..9e41e00 100644 --- a/include/exceptions.h +++ b/include/exceptions.h @@ -79,6 +79,20 @@ namespace YAML : RepresentationException(line_, column_, ErrorMsg::KEY_NOT_FOUND) {} }; + template + class TypedKeyNotFound: public KeyNotFound { + public: + TypedKeyNotFound(int line_, int column_, const T& key_) + : KeyNotFound(line_, column_), key(key_) {} + + T key; + }; + + template + TypedKeyNotFound MakeTypedKeyNotFound(int line, int column, const T& key) { + return TypedKeyNotFound (line, column, key); + } + class BadDereference: public RepresentationException { public: BadDereference() diff --git a/include/node.h b/include/node.h index cb627fe..8900382 100644 --- a/include/node.h +++ b/include/node.h @@ -119,7 +119,7 @@ namespace YAML } } - throw KeyNotFound(m_line, m_column); + throw MakeTypedKeyNotFound(m_line, m_column, key); } template diff --git a/yaml-reader/main.cpp b/yaml-reader/main.cpp index 6038d14..b2c20bb 100644 --- a/yaml-reader/main.cpp +++ b/yaml-reader/main.cpp @@ -11,11 +11,13 @@ void run() YAML::Parser parser(fin); YAML::Node doc; parser.GetNextDocument(doc); - for(unsigned i=0;i> value; - std::cout << (value ? "true" : "false") << "\n"; - } + + std::cout << "name: " << doc["name"] << "\n"; + std::cout << "age: " << doc["age"] << "\n"; + } catch(YAML::TypedKeyNotFound & e) { + std::cout << "Key '" << e.key << "' not found at line " << e.line+1 << ", col " << e.column+1 << "\n"; + } catch(YAML::KeyNotFound& e) { + std::cout << "Key not found at line " << e.line+1 << ", col " << e.column+1 << "\n"; } catch(YAML::Exception& e) { std::cout << "Error at line " << e.line+1 << ", col " << e.column+1 << ": " << e.msg << "\n"; } diff --git a/yaml-reader/tests/test.yaml b/yaml-reader/tests/test.yaml index 34499d1..c266abf 100644 --- a/yaml-reader/tests/test.yaml +++ b/yaml-reader/tests/test.yaml @@ -1,7 +1,3 @@ -- true -- n -- Off -- YES -- on -- FALSE -- FaLse +name: Brett Favre +position: QB +teams: [ Falcons, Packers, Jets ] \ No newline at end of file