- C++ Throw std::string as exceptions
- Related
- Throw Exceptions With Message in C++
- Throw Exceptions With Message Using the Standard C++ Exception — Invalid Argument
- Import Packages
- Method to Throw Exception
- Main Method
- Throw Exceptions With Message Using the Standard C++ Exception — Nested Exception
- Import Packages
- Member Methods
- Use Runtime Error to Throw Exceptions With Message in C++
- Import Packages
- Public Class
- Macros and Exception Throwing
- Main Method
- Conclusion
- Related Article — C++ Exception
C++ Throw std::string as exceptions
We can throw an exception of a different type, std::string for example:
#include #include int main()/* w w w . d e m o 2 s .c o m */ < try < std::cout "We throw an exception of type string, for example." '\n'; std::cout "This signals that something went wrong." '\n'; throw std::string< "Some string error" >; // throw an exception // if there is an error > catch (const std::string& e) < // catch and handle the exception std::cout "String exception raised!." '\n'; std::cout "The exception has a value of: " << e '\n'; > >
Related
demo2s.com | Email: | Demo Source and Support. All rights reserved.
Throw Exceptions With Message in C++
- Throw Exceptions With Message Using the Standard C++ Exception — Invalid Argument
- Throw Exceptions With Message Using the Standard C++ Exception — Nested Exception
- Use Runtime Error to Throw Exceptions With Message in C++
- Conclusion
This article will explain how to throw exceptions with a variable message in C++. Exception throw is the process of shifting control of the program to avoid crashes or overflow.
It is executed by placing an exception throw inside the program where a problem might occur. There are several exception-handling keywords in C++, but this article will look at how to throw exceptions with a variable message.
Throw Exceptions With Message Using the Standard C++ Exception — Invalid Argument
This program uses an invalid argument exception from standard exceptions of C++ to throw exceptions with a variable message.
Import Packages
The program uses two import packages, stdexcept to include standard C++ exceptions and iostream for input and output operations.
Method to Throw Exception
This program defined a function to compare two numbers provided as input and throws an exception case when a negative input is encountered. The standard exception std::invalid_argument is used here.
In this program, a method compare is defined with two integer values, var_a and var_b , as parameters. This uses if to check for a negative number (a, b, or both) and throws an exception if so.
if (var_a 0 || var_b 0) throw std::invalid_argument("Negative value encountered");
Main Method
The main method uses the try-catch exception keywords to throw valid exceptions.
The exception handling is executed by calling the method compare inside try blocks. As the inputs (-1,3) have a negative number, the try block will send the argument to the catch block, which throws exceptions with a variable message and prints the message.
#include #include using namespace std; int check_neg( int var_a, int var_b) if (var_a 0 || var_b 0) throw std::invalid_argument("Negative value encountered"); > return 0; > int main() try compare( -1, 3 ); > catch( const std::invalid_argument& e ) std::cout<"booh!"; > >
booh! -------------------------------- Process exited after 0.006709 seconds with return value 0 Press any key to continue . . .
Throw Exceptions With Message Using the Standard C++ Exception — Nested Exception
Exceptions can be nested with each other to display multiple messages of exception throws consecutively. The program in this section wraps error messages in nested exceptions, then throws exceptions with a variable message in each occurrence and displays them together.
Import Packages
Member Methods
The program has three member functions: print_exception , open_file , and run .
It has two public parameters — std::exception& ex to catch std exceptions and an integer variable stage that is initialized with the value zero. Inside the method, the first line std::cerr is used to print an error message which is Encountered Exception: , but it is placed on levels of nesting using std::string(level,») .
The error message is followed by ex.what where ex is an object of std::exception and ex.what will return an explanatory string on the error that occurred.
The try block uses std::rethrow_if_nested(e) to throw an exception but only in the case where std object ex is derived from a nested exception, which it does in this program.
The catch block uses an std object nestedException to call itself again recursively while increasing the value of stage with 1. The catch(. ) method catches all the exceptions.
void print_exception(const std::exception& ex, int level = 0) std::cerr :: string(level, ' ') <"Encountered Exception: " <'\n'; try std::rethrow_if_nested(ex); > catch(const std::exception& nestedException) print_exception(nestedException, stage+1); > catch(. ) <> >
What happens here in the above code is that it tries to print the explanatory string of the exception. If the function finds it nested, it recurses to print the explanatory of the exception it holds.
The function has a single string parameter std::string& s , which creates a std::string object and transfers an alias s to it.
The try-catch block tries to read a file, catches an exception when the file cannot be loaded, and wraps it in a nested function.
void open_file(const std::string& s) try std::ifstream file(s); file.exceptions(std::ios_base::failbit); > catch(. ) std::throw_with_nested( std::runtime_error("Couldn't open " + s) ); > >
The method void run() calls the method open_file inside the try block. The catch(. ) block catches all the exceptions that arise through std::throw_with_nested .
It raises an exception that combines e with the exception presently being handled.
The exception being handled at the moment becomes the outer exception, and e becomes the nested exception. «run() failed» is the final message printed.
void run() try open_file("nonexistent.file"); > catch(. ) std::throw_with_nested( std::runtime_error("run() failed") ); > >
The main method calls the function run() inside the try block, while inside the catch block, the program calls the method print_exception while passing e as a parameter.
It runs the functions which throw exceptions with a variable message, prints those exceptions caught in a nested format and displays a custom message with each exception throw.
int main() try run(); > catch(const std::exception& e) print_exception(e); > >
#include #include #include #include #include void print_exception(const std::exception& ex, int stage = 0) std::cerr :: string(stage, ' ') <"Encountered Exception: " <'\n'; try std::rethrow_if_nested(ex); > catch(const std::exception& nestedException) print_exception(nestedException, stage+1); > catch(. ) <> > void open_file(const std::string& s) try std::ifstream file(s); file.exceptions(std::ios_base::failbit); > catch(. ) std::throw_with_nested( std::runtime_error("Couldn't open " + s) ); > > void run() try open_file("nonexistent.file"); > catch(. ) std::throw_with_nested( std::runtime_error("run() failed") ); > > int main() try run(); > catch(const std::exception& e) print_exception(e); > >
exception: run() failed exception: Couldn't open nonexistent.file exception: basic_ios::clear -------------------------------- Process exited after 0.05326 seconds with return value 0 Press any key to continue . . .
Use Runtime Error to Throw Exceptions With Message in C++
Custom classes can be used to throw exceptions with a variable message, along with the source file’s path and the line where this error is thrown.
This program uses custom class and macros to output a variable message in the explanatory string using std::runtime_error .
Import Packages
This program requires four import packages, which are:
#include #include #include #include
Public Class
This program uses a constructor class to throw exceptions with a variable message and display that custom message as an explanatory string when the public constructor is called using std::runtime_error .
The first line in the code snippet creates a class my_exception and a new runtime_error object. Along with it, a string object msg is made with global scope, which will be used to pass the explanatory variable string.
The constructor class my_exception is initialized with three parameters: an std string object arg that passes the explanatory string, a pointer object *file of data type char that stores the name of the file, and an integer variable line that stores the line where the exception is thrown.
A string output object is created with std::ostringstream to display an output when this object is called. Lastly, this object is stored inside the variable msg .
The destructor ~my_exception() returns the variable msg as a null-terminated string using return msg.c_str(); .
class my_exception : public std::runtime_error std::string msg; public: my_exception(const std::string &arg, const char *file, int line) : std::runtime_error(arg) std::ostringstream o; o <":" <": " msg = o.str(); > ~my_exception() throw() <> const char *what() const throw() return msg.c_str(); > >;
Macros and Exception Throwing
Here, a macro is defined using #define throw_line(arg) . Calling throw_line() will throw my_exception(arg, __FILE__, __LINE__) .
Method void f() calls macro throw_line and passes the message Oh no! .
#define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__); void f() throw_line("Oh no!"); >
Main Method
The main method will throw exceptions with a variable message by calling the method f() inside the try block. This passes the message block to the method my_exception .
Inside the catch block, a runtime_error object ex is created, which will call the explanatory string using ex.what() .
When the explanatory string is called, the ostream object is called inside the my_exception constructor and returns the file name and error line along with the variable message.
int main() try f(); > catch (const std::runtime_error &ex) std::cout :: endl; > >
#include #include #include #include class my_exception : public std::runtime_error std::string msg; public: my_exception(const std::string &arg, const char *file, int line) : std::runtime_error(arg) std::ostringstream o; o <":" <": " msg = o.str(); > ~my_exception() throw() <> const char *what() const throw() return msg.c_str(); > >; #define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__); void f() throw_line("Oh no!"); > int main() try f(); > catch (const std::runtime_error &ex) std::cout :: endl; > >
D:\c++\std-exceptions\8.cpp:23: Oh no! -------------------------------- Process exited after 0.006875 seconds with return value 0 Press any key to continue . . .
Conclusion
This article explains the various ways to throw exceptions with a variable message and then display the message when exceptions are thrown.
It is hoped that this article helped you learn how to throw exceptions with a variable message, and you will be able to use it in real-life scenarios.
Related Article — C++ Exception
Copyright © 2023. All right reserved