6

I was reading Stroustrup's "Programming -- Principles and Practice Using C++" and found that he included a function without the main curly braces without explaining himself and online people say it is impossible.

I have compiled the code and it works totally fine.

void f()
    try {} 
    catch(...) {}

I expect to get a compiler error from this but I do not and it works fine. I am using C++17.

Dalton Cézane
  • 3,672
  • 2
  • 35
  • 60
csgosmorf
  • 81
  • 4

1 Answers1

7

not require curly braces?

There are curly braces:

void f() try {} catch(...) {}
             ^^

This is a Function-try-block:

A function-try-block associates a sequence of catch clauses with the entire function body

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • 1
    Is there any functional difference with `{ try {} catch(...) {} }`? Ive never seen this before and I'm a bit puzzled as to why its allowed. Only seems to add confusion. – Borgleader Jul 02 '19 at 15:37
  • 6
    @Borgleader there is when used for constructors and you want to catch errors from init-lists, for example. See: https://stackoverflow.com/questions/5612486/when-is-a-function-try-block-useful . No difference for regular functions. – Dan M. Jul 02 '19 at 15:43
  • @Borgleader I've used them just to reduce indent on methods that need to catch almost all exceptions. Quite useful when working with CPP/WinRT for example – Mgetz Jul 02 '19 at 16:37