ROS_INFO_STREAM does not print - c++

I'm trying to use ROS_INFO_STREAM inside an imbricated try...catch but I only have the top-level output
Here's a minimal bunch of code:
void failure()
{
try
{
// throw std::length_error
std::string("abc").substr(10);
}
catch (...)
{
ROS_ERROR_STREAM("ROS failure()"); // print OK
std::cout << "cout failure()" << std::endl; // print OK
throw; // re-throw the exception
}
}
int main()
{
try
{
ROS_ERROR_STREAM("ROS calling"); // print OK
failure(); // will throw
}
catch (...)
{
ROS_ERROR_STREAM("ROS call function"); // <-- NO print
std::cout << "cout call function" << std::endl; // print OK
}
return 0;
}
output:
ROS calling
ROS failure()
cout failure()
cout call function
My guess would be that ROS_ERROR_STREAM looks buffered but as an error output it shouldn't be.
I'm running ROS Groovy

All the macros in rosconsole stop working when ros::shutdown() has been called somewhere in the ROS node.
I can imagine that something like that happens to you: the catch block in the main is probably reached after an error which calls automatically the ros::shutdown() function.
If you would like to maintain the same output format like the one provided by ROS macros, you can use a simple code like this one, but forget to get the code highlighted with colors or other stuff:
std::cout << "[ INFO] [" << ros::Time::now() << "]: main catch" << std::endl;

For ROS_* logging statements to work you have to have either explicitly called ros::init(...) and ros::start(...) beforehand, or as is more common, call ros::init and initialize a ros::NodeHandle. The latter will call ros::start for you.
However, when the last NodeHandle goes out of scope it will call ros::shutdown() and after this point, again you won't be able to use any of the logging macros.

Related

Unhandled exception "terminate called after throwing an instance of" overwrites last line of console

If you throw an unhandled exception out of main like this:
#include <stdexcept>
#include <iostream>
int main()
{
std::cout << "Hello World 1" << std::endl;
throw new std::invalid_argument("A");
return 0;
}
... then the process will terminate with the message "terminate called after throwing an instance of 'std::invalid_argument*'".
You will actually see this on the console:
Hello World 1
terminate called after throwing an instance of 'std::invalid_argument*'
If you print some more text without std::endl and then throw the exception:
#include <stdexcept>
#include <iostream>
int main()
{
std::cout << "Hello World 1" << std::endl;
std::cout << "Hello World 2";
throw new std::invalid_argument("A");
return 0;
}
... then you won't see the second line on the console:
Hello World 1
terminate called after throwing an instance of 'std::invalid_argument*'
It seems that this error message overwrites the last line, e.g. by printing \r before it.
How can this behavior be fixed?
The second line is not actually overwritten by the message, it never reaches the console!
The problem is that std::cout buffers its output and that this buffer is not flushed if the process terminates. (The error message is actually printed to standard error, not standard output.) And that problem was already discovered:
Is it possible to make std::cout flush automatically before program termination in various failure cases (e.g., exception)
In my case I used this to forcefully flush the buffer:
std::terminate_handler oldTerminateHandler;
void newTerminateHandler()
{
std::cout << std::endl;
if (oldTerminateHandler != nullptr)
{
oldTerminateHandler();
}
}
int main()
{
oldTerminateHandler = std::set_terminate(&newTerminateHandler);
//...
}

Do you need to know what exception is going to occur to handle them in C++?

<C++>In exception handling, do you need to know what exception and where an exception is going to occur? Can you make a code which will print and notify us that an exception occurred somewhere in the program. I mean I have a program in which I don't know if an exception will occur or not, if one was to occur, then it will print to notify us.
Exception handling is something you should design for, and in fact it works very well together with RAII (https://en.cppreference.com/w/cpp/language/raii).
(Notr On embedded platforms using exceptions, is not so popular because of some runtime overhead). What I personally like about exceptions is that it separates error handling from the normal program flow (there will be hardly any if then else checks when done right)
// Exception handling should be part of your overal design.And many standard library functions can throw exceptions, It is always up to you where you handle them.
#include <iostream>
#include <string>
#include <stdexcept>
int get_int_with_local_exception_handling()
{
do
{
try
{
std::cout << "Input an integer (local exception handling, enter a text for exception): ";
std::string input;
std::cin >> input;
// stoi is a function that can throw exceptions
// look at the documentation https://en.cppreference.com/w/cpp/string/basic_string/stol
// and look for exceptions.
//
int value = std::stoi(input);
// if input was ok, no exception was thrown so we can return the value to the client.
return value;
}
// catch by const reference, it avoids copies of the exception
// and makes sure you cannot change the content
catch (const std::invalid_argument& e)
{
// std::exceptions always have a what function with readable info
std::cout << "handling std::invalid_argument, " << e.what() << "\n";
}
catch (const std::out_of_range& e)
{
std::cout << "handling std::out_of_range, " << e.what() << "\n";
}
} while (true);
}
int get_int_no_exception_handling()
{
std::cout << "Input an integer (without exception handling, enter a text for exception): ";
std::string input;
std::cin >> input;
int value = std::stoi(input);
return value;
}
int main()
{
try
{
// this function shows you can handle exceptions locally
// to keep program running
auto value1 = get_int_with_local_exception_handling();
std::cout << "your for input was : " << value1 << "\n";
// this function shows that exceptions can be thrown without
// catching, but then the end up on the next exception handler
// on the stack, which in this case is the one in main
auto value2 = get_int_no_exception_handling();
std::cout << "your input was : " << value1 << "\n";
return 0;
}
catch (const std::exception& e)
{
std::cout << "Unhandled exception caught, program terminating : " << e.what() << "\n";
return -1;
}
catch (...)
{
std::cout << "Unknown, and unhandled exception caught, program terminating\n";
}
}
Yes and no.
No, because any exception thrown via throw some_exception; can be catched via catch(...).
Yes, because catch(...) is not very useful. You only know that there was an excpetion but not more.
Typically exceptions carry information on the cause that you want to use in the catch. Only as a last resort or when you need to make abolutely sure not to miss any excpetion you should use catch(...):
try {
might_throw_unknown_exceptions();
} catch(std::exception& err) {
std::cout << "there was a runtime error: " << err.what();
} catch(...) {
std::cout << "an unknown excpetion was thrown.";
}
The C++ standard library uses inheritance only sparingly. Exceptions is only place where it is used extensively: All standard exceptions inherit from std::exception and it is good practice to inherit also custom exceptions from it.

How to terminate an application when an error happnes?

I am using a Graphics Library called Irrlicht
at some point i have to write this code
if(!device){
//error code here`
}
i am not in the main function but want to close the application when this error happens
please keep in mind that I am a beginner so this question might sound dumb
i see some people do this:
int main(){
if(!device){
return 1;
}
return 0;
}
i am not in the main function and want to exit the application outside of the main function
The following example give you an idea about some of the possibilities.
You can simply copy and paste it and play around with it. Simply use only one line of the "termination actions" like throw or exit. If you don't have the try catch block in the main function, your application will also terminate because the exception will not be caught.
struct DeviceNotAvailable {};
struct SomeOtherError{};
void func()
{
void* device = nullptr; // only for debug
if (!device)
{
// use only ONE of the following lines:
throw( DeviceNotAvailable{} );
//throw( SomeOtherError{} );
//abort();
//exit(-1);
}
}
int main()
{
// if you remove the try and catch, your app will terminate if you
// throw somewhere
try
{
func();
}
catch(DeviceNotAvailable)
{
std::cerr << "No device available" << std::endl;
}
catch(SomeOtherError)
{
std::cerr << "Some other error" << std::endl;
}
std::cout << "normal termination" << std::endl;
}

Why do I get memory access violation when using threads in Pybind11?

I created a C++ wrapper to access my Python modules. everything is working until I try to use threads in my application.
On my Python module there is a method which reads from a webcam (so its uses an infinite loop) and I send callbacks from C++ to get the image and other needed information from it.
Since we have a blocking method here, I decided to use threads.
The threading on Python part seems not to be working on the C++ side that is if I call the async counter part of the webcam_feed loop, none of my callbacks are actually executed (on python part the routines are all executed however, it seems it doesn't reach to C++ section somehow. I don't get any feedback in C++ side, however, on Python part, those routines responsible for executing the callbacks save the info to the disk so I know for sure they are executed).
I asked a separate question for it here.
Therefore I decided to use the threading inside C++ client. However, whenever I execute the code (given below), I get an access violation whenever I want to use any methods after the thread is started.
Here are the sample callbacks I have for now:
void default_callback(bool status, std::string id, py::array_t<uint8_t>& img)
{
auto rows = img.shape(0);
auto cols = img.shape(1);
auto type = CV_8UC3;
cv::Mat img1(rows, cols, type, img.mutable_data());
cv::imshow("from callback", img1);
cv::waitKey(1);
auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << "\narg1: " << status << " arg2: " << id << " arg3: " << typeid(img).name() << " " << ctime(&timenow) << std::endl;
}
void default_c_callback_temporary(bool status, char* message)
{
std::cout << "status is: " << status << " id/name: " << message << " ptr:" << "" << std::endl;
std::ofstream myfile;
myfile.open("example.txt");
myfile << "Writing this to a file: " << status << message << std::endl;
myfile.close();
}
And this is the actual test
void thread_test_start(Core* core)
{
try
{
core->SetCpuAffinity(2);
core->AddCallback(default_callback);
core->AddCallback_C_tmp(default_c_callback_temporary);
//set true to run the async version (implemented in python)
core->Start(false);
}
catch (const std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
}
int main()
{
Core* core = new Core(false);
std::thread t(thread_test_start, core);
py::print(core->GetCallbacks());
std::cout << "\nGet C Callbacks:\n";
py::print(core->GetCallbacks_C_tmp());
std::cout << "\nEverything done. press Enter to Exit";
t.join();
std::getchar();
return 0;
}
The call to core->GetCallbacks() causes the memory access violation:
Exception thrown at 0x000000006FCC6D80 (python36.dll) in TestDLL.exe: 0xC0000005: Access violation reading location 0x0000000000000010.
And here is a snapshot showing the access violation error inside VS2019:
Doing something like this is also the same :
void thread_test_start2()
{
try
{
Core* core = new Core(false);
core->SetCpuAffinity(2);
core->AddCallback(default_callback);
core->AddCallback_C_tmp(default_c_callback_temporary);
std::thread t(&Core::Start, core, false);
py::print(core->GetCallbacks());
std::cout << "\nGet C Callbacks:\n";
py::print(core->GetCallbacks_C_tmp());
t.join();
}
catch (const std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
}
results in :
Exception thrown at 0x000000006FCC0CDF (python36.dll) in TestDLL.exe: 0xC0000005: Access violation writing location 0x0000000000000020.
like the former one.
Why am I getting this error ? Can we not use threading with Pybind11? What am I missing here?
Here is a sample project to re-create this issue : https://workupload.com/file/6LmfRtbztHK
The reason for memory access violations were due to trying to run methods using different threads. That is, all Pybind11 related methods (methods that use Pybind11) need to be executed under the very same thread it seems.
Therefore executing some portion of the code under one thread and trying to execute some other methods in the main thread will result in memory access violation.
In order to get around this, I ended up implementing a simple dispatcher in one callback where any method that needs to be run, first sets a flag, then each time the callback is run, the flag is checked and the corresponding method is run.
int flag=0;
void callback(...)
{
switch(flag)
{
case 1: //e.g. stop
core->stop();
break;
case 2: // e.g. get_callbacks()
core->get_callbacks();
break;
case 3:
//some other op
break;
....
}
//reset flag
flag = 0;
}

Global exception handling in C++

Can i implement global exception handling in C++?
My requirement is try...catch block is not used in a piece of code then there should be a global exception handler which will handle all uncaught exception.
Can i achieve it, please give your valuable suggestion : )
I always wrap the outer-most function in a try-catch like this:
int main()
{
try {
// start your program/function
Program program; program.Run();
}
catch (std::exception& ex) {
std::cerr << ex.what() << std::endl;
}
catch (...) {
std::cerr << "Caught unknown exception." << std::endl;
}
}
This will catch everything. Good exception handling in C++ is not about writing try-catch all over, but to catch where you know how to handle it (like you seem to want to do). In this case the only thing to do is to write the error message to stderr so the user can act on it.
you can use a combination of set_terminate and current_exception()
i wanted to do the same, here's what i came up with
std::set_terminate([]() -> void {
std::cerr << "terminate called after throwing an instance of ";
try
{
std::rethrow_exception(std::current_exception());
}
catch (const std::exception &ex)
{
std::cerr << typeid(ex).name() << std::endl;
std::cerr << " what(): " << ex.what() << std::endl;
}
catch (...)
{
std::cerr << typeid(std::current_exception()).name() << std::endl;
std::cerr << " ...something, not an exception, dunno what." << std::endl;
}
std::cerr << "errno: " << errno << ": " << std::strerror(errno) << std::endl;
std::abort();
});
in addition to checking what(), it also checks ernno/std::strerror() - in the future i intend to add stack traces as well through exeinfo/backtrace() too
the catch(...) is in case someone threw something other than exception.. for example throw 1; (throw int :| )
In C++ the terminate function is called when an exception is uncaught. You can install your own terminate handler with the set_terminate function. The downside is that your terminate handler may never return; it must terminate your program with some operating system primitive. The default is just to call abort()
When an exception is raised, if is not caught at that point, it goes up the hierarchy until it is actually caught. If there is no code to handle the exception the program terminates.
You can run specific code before termination to do cleanup by using your own handlers of set_unexpected or set_terminate