Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do try..catch blocks require braces?

While in other statements like if ... else you can avoid braces if there is only one instruction in a block, you cannot do that with try ... catch blocks: the compiler doesn't buy it. For instance:

try     do_something_risky(); catch (...)     std::cerr << "Blast!" << std::endl; 

With the code above, g++ simply says it expects a '{' before do_something_risky(). Why this difference of behavior between try ... catch and, say, if ... else ?

Thanks!

like image 363
Bidou Avatar asked Jun 09 '10 18:06

Bidou


People also ask

What is the point of a try catch block?

Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.

Why should I not wrap every block in try catch?

Exponentially because if each method branches in two different ways then every time you call another method you're squaring the previous number of potential outcomes. By the time you've called five methods you are up to 256 possible outcomes at a minimum.

Is it mandatory to have Catch block with try?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.

Is it bad practice to use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.


2 Answers

Straight from the C++ spec:

try-block:     try compound-statement handler-seq 

As you can see, all try-blocks expect a compound-statement. By definition a compound statement is multiple statements wrapped in braces.

Have everything in a compound-statement ensures that a new scope is generated for the try-block. It also makes everything slightly easier to read in my opinion.

You can check it yourself on page 359 of the C++ Language Specification

like image 127
Justin Niessner Avatar answered Sep 23 '22 17:09

Justin Niessner


Not sure why, but one benefit is that there is no dangling-catch issue. See dangling-else for an ambiguity that can arise when braces are optional.

like image 38
R Samuel Klatchko Avatar answered Sep 23 '22 17:09

R Samuel Klatchko