I am new on Linux and would like to know the command line that would allow me to have see the interface of the smthg::smthg1::smthg2::smthg3() method in order to see if I am correctly catching an exception.
You can launch the following command to find that :
grep -rn "smthg::smthg1::smthg2::smthg3()"
It will find the all lines matching the specified pattern.
Edit : One way to know if you catch an exception at runtime, it's to print one message like this :
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
try {
throw 20;
}catch(int x) {
cout << "Exception catch with status " << x << endl;
}
return 0;
}
If the message is printed then the exception is catched else it's not.
Related
I have just come across a strange behavior of the Xerces-C library which I do not understand. The following code, which has already been seen in loads of examples, works for me:
#include <iostream>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace std;
using namespace xercesc;
int main (int argc, char* argv[])
{
try {
XMLPlatformUtils::Initialize ();
XercesDOMParser* parser = new XercesDOMParser ();
// here one might want to add some useful operations
delete parser;
XMLPlatformUtils::Terminate ();
}
catch (...) {
cout << "caught some exception" << endl;
}
return 0;
}
Surely, this code does not do many meaningful things. But it runs and in particular terminates cleanly.
Now, I was trying to avoid the new/delete and switch to a scoped object, like so:
#include <iostream>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace std;
using namespace xercesc;
int main (int argc, char* argv[])
{
try {
XMLPlatformUtils::Initialize ();
XercesDOMParser parser;
// here one might want to add some useful operations
XMLPlatformUtils::Terminate ();
}
catch (XMLException& exc) {
cout << "caught an XMLException" << endl;
}
catch (...) {
cout << "caught an exception" << endl;
}
return 0;
}
This or similar code has also been seen many times. However, when I run it, it creates a segfault after (?) XMLPlatformUtils::Terminate() (that's at least, what my debugger is suggesting). Still, I have successfully worked with a parser object created in that way. And if I omit the call to Terminate(), I see my process terminate cleanly.
Does anyone have a clue what I am doing wrong here?
Paul's comment already gave the correct answer and his explanation why does make sense. So for completeness, here is the code that actually works (note the explicitly created inner scope):
#include <iostream>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace std;
using namespace xercesc;
int main (int argc, char* argv[])
{
try {
XMLPlatformUtils::Initialize ();
{
XercesDOMParser parser;
// here one might want to add some useful operations
}
XMLPlatformUtils::Terminate ();
}
catch (XMLException& exc) {
cout << "caught an XMLException" << endl;
}
catch (...) {
cout << "caught an exception" << endl;
}
return 0;
}
Thank you Paul!
I'm trying to figure out the best way to exit my program cleanly after printing the CLI help information in my program. Currently it looks like this.
int main(int argc, *char[] argv) {
try {
std::string settings_file = process_args(argc, argv);
do_more_stuff();
...
...
} catch (...) {
std::cerr << "Error" << std::endl;
return (EXIT_FAILURE)
}
}
std::string process_args(int argc, char *argv[]) {
boost::program_options::options_description desc("Program options");
desc.add_options()("help,h", "Print usage message")(
"settings,s", boost::program_options::value<std::string>(),
"Specify settings file");
boost::program_options::variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
---->!!!!!!!! WHAT DO I DO HERE TO GET OUT !!!!!!!!<----
}
if (vm.count("settings")) {
std::cout << "Settings file " << vm["settings"].as<std::string() << std::endl;
return vm["settings"].as<std::string>();
} else {
throw std::runtime_error("Settings file must be specified.");
}
}
So my question is after I print the CLI 'help' message what do I do to exit my program?
Should my function not be returning std::string and just return an error code?
Should I throw an exception and catch it in main and then exit?
Is there a much nicer / better way to do it?
Thanks in advance.
Another better way in my opinion, according to this post : C++ catching all exceptions
#include <cstdlib>
#include <iostream>
#include <stdexcept>
static bool checkHelp(char * const argv[])
{
bool usage = (!strcmp(argv[1], "-h") or !strcmp(argv[1], "--help"));
if (usage) {
std::cout << "Print your usage" << std::endl;
}
return usage;
}
int main(int argc, char *argv[])
{
/* Set eval to default value */
int eval = EXIT_SUCCESS;
try {
if (!checkHelp(argv)) {
/*
** do some stuff here
*/
}
} catch (std::exception const &err) {
/* update eval on throwed exceptions */
eval = EXIT_FAILURE;
std::cerr << "error: " << err.what() << std::endl;
}
return eval;
}
Doing by this way, you can manage all your program execution in error context and choose what to do : update return value, do other stuff, etc.
You don't break your main thread and prevent you from memory errors/leaks without exit by exit() function.
1) eval (for 'exit value') is instancianted and destroyed with main context. In accordance with the type of main's return value, we have to change it's value if an error occurred before returning it while exit the program.
2) In my example, I send argv to the checkHelp function who returned true if the first argument of my software (argv[1] here) is equal to "-h" or "--help", if not checkHelp returns false. You can also do a loop on all argv arguments received by main.
3) Finally, catch (std::exception const &err) allows you to get your throwed exception by reference and print his message. So, you are using your main try/catch block in all his integrity.
Here is my personal opinion: there isn't a best practice way but I prefer the first approach!
1. Approach:
https://en.cppreference.com/w/cpp/utility/program/exit
You can call the following function:
std::exit( EXIT_FAILURE );
2. Approach:
Create an exception.
throw "Please call me with some parameters!"
But I do not prefer this approach. For some users the exception looks like there is an internal software error...
First thing,sorry my bad english and any mistakes in asking.
I've searched it a lot,but i was not able to explain in simple words.
I work with Linux servers and command line, i'm used to calling programs through it like
./program foo -u adm -p 123
But i always wondered how make programs to act like that,i mean call a specific function and write parameters without needing to open program itself.
In other words.
If i code a C++ like that,and compile
#include <iostream>
using namespace std;
void SayHello(string Name)
{
cout << " Hello " << Name;
}
how can i call it through the command line like
./Program SayHello CARLOS
Sorry about my ignorance,but it's something that i want to learn.
Thanks for your attention
If you want to call a function of your program based on the arguments, you could do something like:
int main(int argc, char* argv[]) {
if(argc > 2){
if(strcmp(argv[1], "SayHello") == 0){
SayHello(argv[2]);
}
}
return 0;
}
Of course this is just a sketch and i can be improved if what you want to achieve is more complex.
You could also build a more dynamic solution if you want other functions than the "SayHello" one to be callable too.
int main( int argc, char** argv )
Here argc refers to the number of argument (arg count)
argv refers to the argument array ("char*" array) (arg value)
Calling your program from command line will result in a main entry with these parameters ; it remains to parse them and launch the command accordingly.
void main() {
char *name[] = {
"./program",
"-c",
"foo -u adm -p 123",
NULL
};
execvp(name[0], name);
}
There you go every executable needs a main function which is the entry point for execution.
#include <iostream>
#include <string>
using namespace std;
void SayHello(string Name)
{
cout << " Hello " << Name;
}
int main(int argc, char* argv[])
{
if (argc > 1)
SayHello(argv[1]);
}
To compile this do
$g++ hello.cpp
It should produce a.out on Linux.
To run it
./a.out "World!"
I am new to protobuf (C++) and try to write first test program with protobuf.
Code is
#include <cstdlib>
#include <iostream>
#include "proto/req.pb.h"
using namespace std;
using namespace google::protobuf;
int main(int argc, char** argv) {
std::string s = "asdfasdf";
auto MyLogHandler = [] (google::protobuf::LogLevel level, const char* filename, int line, const std::string& message)
{
std::cout << "message " << message << std::endl;
};
google::protobuf::SetLogHandler(MyLogHandler);
Request req;
if ( req.ParseFromString(s)){
cout << "Parse - OK" << endl;
}else{
cout << "Parse - ERROR" << endl;
}
return 0;
}
When program runs - it show only error message, but not any reason about it. How can I get a reason for the error?
There are two reasons Protobuf parsing can fail:
The input data is missing required fields. In this case the Protobuf library writes a log message describing the problem and then returns false. Your log handler will receive the error message in this case.
The input data is not a valid Protobuf (it is corrupt, or was never a protobuf in the first place). In this case the Protobuf library simply returns false without any error message. There is really no useful information that the library could provide here. If this happens to you, the best way to debug is to dump the exact bytes right after you serialized the message and right before you parsed it, then look for differences.
I was writing a code for exception handling on Visual C++ 2010 .Here is the code
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {
cout << "Caught Exception #: " << i << '\n';
}
}
int main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}
The Program executed properly and the output was the as expected.But when I pressed the close button for closing the console then an error came that cmd has stopped working
.Then I ran my previous code that executed properly ,they also gave the same error
.
Can anybody tell why it is happening?Is it a problem with the Visual c++ 2010 or the code
I think your problem is not with your code. The problem is within your compiler tool chain. You probably are using Qt, and the tool chain has a problem causing this. Google the message you get when you crash with your IDE.
Here's a simple experiment to prove what I'm saying: just run this code:
int main()
{
cout << "Start\n";
cout << "End";
return 0;
}
And your program will crash, which means you have no problems with exceptions or anything else in your code, but with your tool chain.