Why does Try-Catch require curly braces

前端 未结 10 1151
一整个雨季
一整个雨季 2020-12-13 23:57

Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn\'t the language allow:

int i;
string s = DateT         


        
10条回答
  •  长情又很酷
    2020-12-14 00:37

    Probably to discourage overuse. A try-catch block is big and ugly, and you're going to notice when you're using it. This mirrors the effect that a catch has on your application's performance - catching an exception is extremely slow compared to a simple boolean test.

    In general you should avoid errors, not handle them. In the example you give, a much more efficient method would be to use

    if(!int.TryParse(s, out i))
     i=0;
    

提交回复
热议问题