c++ - try\catch block in the main() function without brackets -


visual studio 2015; c++ language.

i remember read somewhere entry point (i.e. main method) possible write this:

#include <iostream> using namespace std;  int main() try{   return 0; // here... } catch (...){   cout << "i 'catch'..." << endl; // row wasn't called!   return 1; // oops... next `f10` key pressing jumps "try"    // block row! } 

i.e. @ case try\catch block located not in brackets:

int main() { // start bracket   try{     return 0;   }   catch (...){     return 1;   } } // end bracket 

both cases compiled , work too, but... in first variant, when step step pressing f10 key after try block catch block also. second variant of code haven't such behaviour.

why happen?

your construction function-try-block , defined in drafs n4296 c++ 11 specification @ 8.4 function definitions [dcl.fct.def.general] with:

function definitions have form

  • function-definition:
    • attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt function-body
  • function-body:
    • ctor-initializeropt compound-statement
    • function-try-block
    • = default ;
    • = delete ;

and later in 15 exception handling [except] with:

function-try-block:

  • try ctor-initializeropt compound-statement handler-seq

examples suggest normal usage function-try-block should ctor, valid normal function (and main syntactically mere function)

it valid , works normally, meaning catch block evaluated if exception occurs in ctor-initializeropt on in compound-statement. can confirm in code adding prints in blocks or testing return value.

in unix system

foo echo $? 

should echo 0

in windows system under cmd.exe windows

foo.exe if errorlevel 1 echo "catch block" 

should not output catch block

if debugger lets execute instructions in catch block... not c++ 11 conformant!

but known when exiting block, msvc debugger puts cursor on last line of block, assume is happening here because last line of function-try-block is last line of catch.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -