1 // Copyright (c) 2012-2014 Konstantin Isakov <ikm@zbackup.org> and ZBackup contributors, see CONTRIBUTORS 2 // Part of ZBackup. Licensed under GNU GPLv2 or later + OpenSSL, see LICENSE 3 4 #ifndef EX_HH_INCLUDED__ 5 #define EX_HH_INCLUDED__ 6 7 #include <exception> 8 #include <stdio.h> 9 #include <string> 10 11 /// A way to declare an exception class fast 12 /// Do like this: 13 /// DEF_EX( exErrorInFoo, "An error in foo encountered", std::exception ) 14 /// DEF_EX( exFooNotFound, "Foo was not found", exErrorInFoo ) 15 16 #define DEF_EX( exName, exDescription, exParent ) \ 17 class exName: public exParent { \ 18 public: \ 19 virtual const char * what() const throw() { return (exDescription); } \ 20 virtual ~exName() throw() {} }; 21 22 /// Same as DEF_EX, but takes a runtime string argument, which gets concatenated 23 /// with the description. 24 /// 25 /// DEF_EX_STR( exCantOpen, "can't open file", std::exception ) 26 /// ... 27 /// throw exCantOpen( "example.txt" ); 28 /// 29 /// what() would return "can't open file example.txt" 30 31 #define DEF_EX_STR( exName, exDescription, exParent ) \ 32 class exName: public exParent { \ 33 std::string value; \ 34 public: \ 35 exName( std::string const & value_ ): value( std::string( exDescription ) + " " + value_ ) {} \ 36 exName( char const * value_, unsigned size ): value( std::string( exDescription ) + " " + std::string( value_, size ) ) {} \ 37 virtual const char * what() const throw() { return value.c_str(); } \ 38 virtual ~exName() throw() {} }; 39 40 /// An exception class to wrap leave code into an std::exception 41 class exLeaveWrapped: public std::exception 42 { 43 char buf[ 32 ]; 44 45 public: 46 exLeaveWrapped(int error)47 exLeaveWrapped( int error ) 48 { sprintf( buf, "%d", error ); } 49 what() const50 char const * what() const throw() 51 { return buf; } 52 }; 53 54 #endif 55