使用try with catch时未初始化局部变量,但在最终与catch一起使用时初始化。为什么? [英] Local variable not initialized when using try with catch but is initialized when finally is used with catch . Why ?
问题描述
public static void main (String args[] )
{
int a ;
try
{
a=4 ;
}
finally {
}
System.out.println (a ) ;
}
为什么在最终使用时这不会产生编译时错误?我无法理解这背后的逻辑。我已经理解了当我们使用catch而不是finally时的情况并且它给出了编译时错误。但为什么不在这里?
我尝试过的事情:
我在Netbeans IDE上运行它。
Why this does not give a compile time error when finally is used ? I am not able to understand the logic behind this . I have understood the case when we use catch instead of finally and it gives a compile time error . But why not here ?
What I have tried:
I have run this on Netbeans IDE .
推荐答案
想一想:什么是try ... catch块意味着什么?
它捕获异常,并将执行直接转移到catch块代码。
因此,如果您的代码如下所示:
Think about it: what is a try...catch block meant to do?
It catches exceptions, and diverts execution directly to the catch block code.
So if your code looks like this:
int a ;
try
{
a=4 ;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
然后系统可以看到未初始化a的执行路径:当分配中出现问题时。在你的例子中不太可能发生,但在更复杂的情况下它可能会发生:
Then the system can "see" an execution path where a is not initialised: when a problem occurs in the assignment. It's not likely to happen in your example, but it very much could in a more complex case:
int a ;
try
{
a=GetValue();
}
catch (Exception ex)
{
...
}
如果GetValue中发生异常,则永远不会设置a的值。
使用finally是不同的:它不会捕获异常,因此要么执行赋值,要么执行后的代码尝试... finally块不会(因为异常未处理,一旦最终代码完成,它由更高级别的方法处理)。
这与昨天的问题非常相似:为什么在使用inputstreamreader类时必须初始化变量x? [ ^ ]
If an exception occurs in GetValue, the value of a is never set.
Using finally is different: it doesn't catch an exception, so either the assignment will be executed or the code after the try...finally block will not (as the exception isn't handled, it it dealt with by a higher level method once the finally code is complete).
This is very much the same problem you had yesterday: Why the variable x has to be initialized when using inputstreamreader class ?[^]
这篇关于使用try with catch时未初始化局部变量,但在最终与catch一起使用时初始化。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!