When is a function try block useful?

后端 未结 6 1511
忘了有多久
忘了有多久 2020-11-30 06:31

I\'m wondering when programmers use function try blocks. When is it useful?

void f(int i)
try
{
   if ( i  < 0 ) 
      throw \"less than zero\";
   std::         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 06:51

    Aside from the functional uses mentioned, you can use the function-try-block to save yourself one level of indentation. (Ack, an answer about coding styles!)

    Typically you see examples with the function-try-block like so:

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

    Where the function scope is indented to the same level as if there were no function-try-block. This can be useful when:

    • you have an 80 character column limit and would have to wrap lines given the extra indentation.
    • you are trying to retrofit some existing function with try catch and don't want to touch all the lines of the function. (Yeah, we could just use git blame -w.)

    Though, for functions that are entirely wrapped with a function-try-block, I would suggest not alternating between some functions using function-try-blocks and some not within the same code base. Consistency is probably more important then line wrapping issues. :)

提交回复
热议问题