为什么尝试捕获需要花括号 [英] Why does Try-Catch require curly braces
问题描述
只是好奇:为什么是尝试在C#抓语法(Java也?)硬编码为多个语句?为什么不语允许:
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 = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1";
try
i = int.Parse(s);
catch
i = 0;
这个例子仅仅是为了微不足道的目的。我知道有 int.TryParse
< 。/ A>
推荐答案
考虑的是,真的有在这里打球三个(或更多)的代码块:
Consider the fact that there are really three (or more) code blocks in play here:
try {}
catch (myexcption)
{}
catch (myotherexception)
{}
finally
{}
记住,这些都是在更大范围内的范围,而不是被逮捕的非法potentually进一步赶上堆栈中的例外。
Keep in mind that these are in the scope of a larger context and the exceptions not caught are potentually caught further up the stack.
请注意,这是基本相同的事情为一类结构,它也有{ }结构
Note that this is basically the same thing as a class construct that also has the {} structure.
例如说你可能有:
try
try
if (iAmnotsane)
beatMe(please);
catch (Exception myexception)
catch (myotherexception)
logerror("howdy")
finally
现在确实是第二个catch属于第一或第二试试?怎么样最后?所以你看到了可选/多部分构成的要求。
NOW does that second catch belong to the first or the second try? What about the finally? SO you see the optional/multiple portions make the requirement.
这篇关于为什么尝试捕获需要花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!