I have a situation like this. In my code, there are countless code blocks like this.
try
{
DoSomething();
}
catch( Ogre::Exception& e )//Yes, I'm using Ogre, but you get the idea :)
{
MessageBoxA( NULL, e.getFullDescription().c_str(), "An exception has occured!",
MB_OK | MB_ICONERROR | MB_TASKMODAL );
}
I don't want to put breakpoint at every catch block. So each time an exception is thrown, a message box show up - I click ok and program close.
What I want is after I click Ok on the message box, Visual studio catch debug in the message box thread and I can see what happens down there in the source code.
Note: I don't know if 'catch debug' is a proper word, when I say 'catch debug', I mean: activate 'Step into' (F11)/'Step over' (F10) feature of Debug mode --> A yellow arrowhead in the margin of a source appears. Maybe the right word is 'break'.
PS: in my situation, I can just use the 'Exception settings' (for VS older than 2015, check this post) to Break When Throw all C++ Exceptions. Then when any C++ exception is throw, my VS 2015 will break to let me see what happens. Yet, I still want to solve this question, maybe there are situations when it is not exception but just message box - then a skill to break after message box is shown is required.
You are underestimating the power of Exception Settings. It allows you to carefully filter out types of the exceptions that you want to intercept. Open Exception Settings window, uncheck "C++ Exceptions" checkbox, select "C++ Exceptions" item (so entire line is highlighted, this will also activate "+" button on toolbar), press "+" button (or use context menu entry) to add Ogre::Exception type to the list of exceptions, check Ogre::Exception checkbox so only it will be intercepted.
If you had used MessageBox macro instead of implicitly using MessageBoxA, then you could have done a macro redefine inserting a DebugBreak() afterwards.
I think what I would try at this point is to place a breakpoint at User32!MessageBoxA. This way you get a break before each message box is executed. Then you F10 that call, which will execute the message box, when you press OK it returns back to debugger and you can inspect your code.
Add comment as the solution:
In VS2017, you could use the new feature called "Using the New Exception Helper" under Tools->Options->Debugging. It could provide much more debugging information than previous version like breaking on the Line of Code or faster breaking for Unhandled Exceptions and others.
If you want to stop the execution right after you enter the catch block, you want to use a function like DebugBreak(). Here is a snippet that you can try:
try
{
throw out_of_range("hello, stackoverflow");
}
catch (exception& e)
{
// Exection wil stop here.
// You will see the exception thrown above in the Output console.
DebugBreak();
}
Note that it will also work on the Release builds, not only in Debug.
EDIT
If you want exactly that yellow arrow, you could use a dirty hack that is VERY, VERY BAD PRACTICE:
try
{
throw out_of_range("hello, stackoverflow");
}
catch (exception& e)
{
// Now you will get the yellow arrow.
// From here, you could acces the call stack console that VS provides.
// By the way, you could have also done that in the previous example.
int b[1];
b[1000] = 0;
}
Related
I've been trying to make a list in Qt that adds and removes integers for my Data Structures class, the teacher asked for a GUI, but I've been struggling a bit with the exception. I have managed to show the error when the list is empty, but the program closes after that, I wanted it to keep running after the warning popup window, but i have no idea how to proceed. I'm using try and catch to do that. Here is one of my remove buttons, this one removes the first int of the list.
void MainWindow::on_removerInicio_clicked()
{
try
{
throw ListaSeq.isEmpty();
}
catch(...)
{
QMessageBox::warning(this,tr("Aviso!"),tr("Lista Vazia!"));
}
ui->listWidget->takeItem(0);
ListaSeq.removeFirst();
nElementos--;
ui->nElementos->setText(QString::number(nElementos));
}
I know it's wrong but I don't know how to fix it, when clicked it shows the warning, but also closes the program. Can you help me?
Edit: Also if i take out the code
ui->listWidget->takeItem(0);
ListaSeq.removeFirst();
nElementos--;
ui->nElementos->setText(QString::number(nElementos));
The programs works fine and return to the mainwindow.
...kind of. As illustrated by this extremely simplistic example,
very rarely (only once reported so far), it happens that one of my applications crashes this way. I want to terminate it as I normally do when an unspecific exception occurs. My strategy is to (low-level) log the problem, then terminate. The application is part of a subsystem and I want to (re)start it, if any problem is detected. It's built with C++-Builder 6 and runs on Windows (XP...7, also 8). I learned that an abort() most probably caused the error message. The application has a GUI, that's why a message box is shown instead of just making an (unblocking) output to stderr.
And as long as the message box isn't accepted by a user, my application keeps obviously running, for example it handles timers (the lifebeats in the above example increase) or inter-process messages, fully unaware about the problem.
After reading some answers to What is the easiest way to make a C++ program crash? and Difference between raise(SIGABRT) and abort() methods, I tried the following
void mySignalHandler(int sig)
{
// low-level error reporting here
exit(-1);
}
void __fastcall TForm1::FormCreate(TObject *Sender)
{
signal(SIGABRT, mySignalHandler);
// some more initialisation here
}
which lets my application terminate properly also if abort() or raise(SIGABRT) is called. (I also wish to prevent Windows from "searching for a solution of the problem".)
Is this (registering a signal handler for abort and calling exit there) reliable from your point of view? ...or at least something one can build upon?
In the C++Builder installation folder, check the following files:
source\cpprtl\Source\misc\errormsg.c - implementation of _ErrorMessage
source\cpprtl\Source\procses\abort.c - implementation of abort, which calls _ErrorMessage
source\cpprtl\Source\misc\assert.c - implementation of _assert, which calls _ErrorMessage
errormsg.c defines an undocumented _messagefunc function pointer that you can set to override the default behavior. Although it's undocumented and not declared in any header files, you can declare it as an extern and access it that way. Sample usage:
extern int (_RTLENTRY * _EXPDATA _messagefunc)(char *msg);
static int LogAndDie(char *msg)
{
LogMessageToSomeFile(msg);
exit(1);
return 0;
}
void InitializeErrorHandling()
{
_messagefunc = LogAndDie;
}
You might be able to use Windows Error Reporting to create a dump of the process, when an unhandled exception causes a termination. Then you can review the dump at your leisure and allow some parent-process or other watchdog to restart your process. If you chose this strategy, you would not try to deal with the failure in your code, but to allow it.
If you want to capture any program exit you should look at atexit(). If you want to capture all termination events then look at std::set_terminate(), if you want to caputure all unexpected exceptions then look at std::set_unexpected(). If you want to capture only abort() you can call signal() with the SIGABRT signal value. You can also wrap your code with try{your code}catch(...){custom event handler}.
I could do some tests, and I only can confirm that registering a SIGABRT signal handler is simply a NOOP.
I tried it with a very simple GUI application written with VS2008 Express. :
no framework, nor .NET but only Win API
one menu with Exit and Fatal
menu managed directly in WndProc
Fatal execute 1/0
Here are the result :
no special action => windows opens a MessageBox indicating a fatal error ...
signal handler for SIGABRT => same MessageBox
C++ try catch(...) => same MessageBox
SEH in WndProc : can intercept the error !
SEH around message loop : can intercept the error !
If I put bot SEH handlers, the most internal (WndProc) catches.
The good new for you is that if is enough to protect the message loop, and you do not have to go into every WndProc.
The bad new is that I do not know C++ builder and cannot say where to find the message loop.
Just to give you a clue, here is how I could protect the message loop in a WinAPI application :
__try {
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER){
::MessageBox(NULL, _T("FATAL"), _T("MAIN"), MB_OK | MB_ICONERROR);
}
That way, I can see my own message box, but nothing else and if I comment my message box the application silently exits.
But ... as the message you show is not original Windows one, I suspect C++ builder to already have such an exception handler in its message loop.
Hope it helps ...
Consider next piece of code:
void CMyDB::Connect()
{
//db_ is an member object of CDatabase class
//connStr is previously defined connection string
db_.OpenEx(connStr, CDatabase::noOdbcDialog);
}
after executing Connect() -- if connection string contained wrong data, then a message box with error description will be shown.
Now if I wrap that call to Connect() in try/catch block no message box will be shown, instead an exception will be thrown:
void CMyDB::Connect()
{
try {
result = db_.OpenEx(connStr, CDatabase::noOdbcDialog);
}
catch(CDBException* e) { }
}
Now, I don't understand how OpenEx() understands that it is being wrapped by try/catch block and there is no need to show message box with error description. I know it somehow related to those MFC specific macro used inside OpenEx() (TRY, CATCH_ALL, etc.) and an AFX_EXCEPTION_LINK structure provided by them, but still can't get the whole picture.
Thanks.
It doesn't know it.
Your catch does swallow the exception, which was (before you add the try/catch) thrown to a top-level catch in your program. This top level catch was showing the Dialog Box with the error message.
I am using CEF3 (chrome embedded framework) in my win32 application, while I am running the application I get a weird error message -
I am coming from a C# development background, and here in C++ I don't see how I can inspect my error and figure out why it's complaining about my code.
How can I check the error message? If not - how you debug this kind of errors in Visual Studio?
This the code which triggering the error -
case WM_CREATE:
{
CefRefPtr<CefClient> clientHandler = new ClientHandler();
RECT rect;
GetClientRect(hWnd, &rect);
CefWindowInfo info;
info.SetAsChild(hWnd, rect);
// Browser initialization settings.
CefBrowserSettings settings;
// Create the new browser window object asynchronously.
std::string startupUrl = "http://www.google.com/";
CefBrowserHost::CreateBrowser(info, clientHandler, startupUrl, settings);
}
break;
I don't want help in CEF3 (but I will appreciate it) I just want to know how to debug this kind of errors in Visual Studio.
The Output window of the debugger tells you what exception was thrown.
Also, you can click "Break" in the dialog that appears and VS will take you to the line on which the exception was thrown. You'll see a yellow arrow to the left of the line.
Finally, if the exception is not fatal, you can catch it and ignore it:
try
{
...
}
catch (const SomeException&)
{
// do nothing
}
I had problems building in Release. The problem was that I didn't called CefInitialize at all.
I have a collection of Boost unit tests I want to run as a console application.
When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run.
I see that if I run in release mode the console window stays up after the program exits, but in debug mode this is not the case.
I do not want to add 'system("pause");' or any other hacks like reading a character to my program. I just want to make Visual Studio pause after running the tests with debugging like it would if I were running in release mode. I would also like it if the output of tests were captured in one of Visual Studio's output windows, but that also seems to be harder than it should be.
How can I do this?
Try to run the application with the Ctrl + F5 combination.
http://connect.microsoft.com/VisualStudio/feedback/details/540969/missing-press-any-key-to-continue-when-lauching-with-ctrl-f5
In the older versions it would default to the console subsystem even if you selected "empty project", but not in 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this). Then select "project" from the menu bar drop down menus, then select "project_name properties" > "configuration properties" > "linker" > "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
Boost test offers the following usage recommendations for Visual Studio that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.
The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump through these errors using usual keyboard shortcuts/mouse clicks you use for compilation error analysis..."
Set a breakpoint on the last line of code.
I just copied from http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787/?prof=required:
The following works for me :-)
/////////////////////////////////////////////////////////////////////////////////////
Here is another reason the console may disappear. And the solution:
With the new Visual Studio 2010 you might see this behavior even when you use Ctrl + F5 aka "start without debugging". This is most likely because you created an "empty project" instead of a "Win32 console application". If you create the project as a "Win32 console application" you can disregard this as it does not apply.
In the older versions it would default to the console subsystem even if you selected "empty project", but not in Visual Studio 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this).
Then select "project" from the menu bar drop down menus, then select "project_name properties" → "configuration properties" → "linker" → "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
/////////////////////////////////////////////////////////////////////////////////////
If it is a console application, use Ctrl + F5.
In Boost.Test there is the --auto_start_dbg parameter for breaking into the debugger when a test fails (on an exception or on an assertion failure). For some reason it doesn't work for me.
See http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html
For this reason I have created my custom test_observer that will break into the debugger when there is an assertion failure or an exception. This is enabled on debug builds when we are running under a debugger.
In one of the source files of my unit test EXE file I have added this code:
#ifdef _DEBUG
#include <boost/test/framework.hpp>
#include <boost/test/test_observer.hpp>
struct BoostUnitTestCrtBreakpointInDebug: boost::unit_test::test_observer
{
BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::register_observer(*this);
}
virtual ~BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::deregister_observer(*this);
}
virtual void assertion_result( bool passed /* passed */ )
{
if (!passed)
BreakIfInDebugger();
}
virtual void exception_caught( boost::execution_exception const& )
{
BreakIfInDebugger();
}
void BreakIfInDebugger()
{
if (IsDebuggerPresent())
{
/**
* Hello, I know you are here staring at the debugger :)
*
* If you got here then there is an exception in your unit
* test code. Walk the call stack to find the actual cause.
*/
_CrtDbgBreak();
}
}
};
BOOST_GLOBAL_FIXTURE(BoostUnitTestCrtBreakpointInDebug);
#endif
You say you don't want to use the system("pause") hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit(). If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit() call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.
Or you could use boost_test "Test Log Output."
http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/user-guide/test-output/test-log.html
Then it won't matter whether the console window shows up at all AND your build logging can preserve the unit testing output as an artifact for examination on failed builds...
Adding the following line will do a simple MS-DOS pause displaying no message.
system("pause >nul | set /p \"=\"");
And there is no need to Ctrl+F5 (which will make your application run in Release Mode)
I would use a "wait"-command for a specific time (milliseconds) of your own choice. The application executes until the line you want to inspect and then continues after the time expired.
Include the <time.h> header:
clock_t wait;
wait = clock();
while (clock() <= (wait + 5000)) // Wait for 5 seconds and then continue
;
wait = 0;
You could also setup your executable as an external tool, and mark the tool for Use output window. That way the output of the tool will be visible within Visual Studio itself, not a separate window.
I start the app with F11 and get a breakpoint somewhere in unit_test_main.ipp (can be assembly code). I use shift-f11 (Step out) to run the unit test and get the next assembly instruction in the CRT (normally in mainCRTStartup()). I use F9 to set a breakpoint at that instruction.
On the next invocation, I can start the app with F5 and the app will break after running the tests, therefore giving me a chance to peek at the console window
Just use a logging library, like log4net, and have it log to a file appender.
Prompt for user input.
https://www.youtube.com/watch?v=NIGhjrWLWBo
shows how to do this for C++. For Node.js, this is taken right from the docs (and it works):
'use strict';
console.log('Hello world');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Press enter to continue...', (answer) => {
rl.close(); /* discard the answer */
});
Do a readline at the end (it's the "forma cochina", like we say in Colombia, but it works):
static void Main(string[] args)
{
.
.
.
String temp = Console.ReadLine();
}