Why does Try-Catch require curly braces

前端 未结 10 1109
一整个雨季
一整个雨季 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:30

    The rational is that it's more maintainable (easier to change, less likely to break, ergo higher quality):

    1. it's clearer, and
    2. it's easier to change because if you need to add a line to your blocks you don't introduce a bug.

    As to why exception handling is different than conditional expressions...

    • If/Else is conditional upon an expression to use one of two (or more If/Else if/Else) paths in the code
    • Try/Catch is part of exception handling, it is not a conditional expression. Try/Catch/Finally operates only when an exception has been thrown inside the scope of the Try block.

    Exception handling will traverse up the stack/scope until it finds a Catch block that will catch the type of exception that was thrown. Forcing scope identifiers makes this check for blocks simplified. Forcing you to scope when dealing with exceptions seems like a good idea, it also is a good indication that this is part of exception handling rather than normal code. Exceptions are exceptions, not something you really want happening normally but know can happen and want to handle when they do happen.

    EDIT: There is one more reason which I can think of, is that CATCH is mandatory after a TRY unlike ELSE. Hence there needs to be definite way to define the TRY block.

提交回复
热议问题