为什么我不能在 try 块中分配对象变量?
为什么我无法在 try
块内分配对象变量?
如果我尝试执行此操作并清理 finally
块中的变量,则会收到编译器错误:“使用未分配的局部变量”。这是没有意义的,因为变量是在 try
块之前声明的,而在 finally
块中我首先检查变量是否为 null
。
为什么下面的代码不能编译?我正在检查 dbc 是否为 null,因此它不可能尝试对未分配的变量执行某些操作。
例如:
DbConnection dbc;
try {
dbc = <some method call returning an open DbConnection>
// do stuff
} catch (Exception e) { // do stuff }
finally {
if (dbc != null) {
dbc.Close();
}
}
Why can't I assign object variables within the try
block?
If I attempt to do this and clean up the variable in the finally
block I get a compiler error: "use of unassigned local variable". This makes no sense because the variable is declared before the try
block, and in the finally
block I am first checking whether the variable is null
.
Why can't the following code compile? I am checking whether dbc
is null
so there's no chance of it trying to do something with an unassigned variable.
eg:
DbConnection dbc;
try {
dbc = <some method call returning an open DbConnection>
// do stuff
} catch (Exception e) { // do stuff }
finally {
if (dbc != null) {
dbc.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将声明更改为
DbConnection dbc = null;
以便编译器可以确定变量已被赋值。 (仅仅声明dbc
与为其分配 null 值不同,您必须明确使用本地值。)现有代码失败的原因是它完全是在设置 dbc 之前可能会发生异常。因此,编译器不能假设 dbc 在执行 finally 块时已被分配。
有关详细信息,请参阅语言规范第 5.3 节有关明确赋值的内容。
http://msdn.microsoft.com/en-us/库/aa691172(VS.71).aspx
Change your declaration to
DbConnection dbc = null;
so the compiler can know for certain that the variable is assigned. (Merely declaringdbc
is not the same as assigning it a value of null, you must be explicit with a local.)The reason your existing code fails is that it is entirely possible for an exception to occur before dbc is set. As such, the compiler cannot assume that dbc is assigned by the time the finally block executes.
For more info, see section 5.3 of the language specification on definite assignment.
http://msdn.microsoft.com/en-us/library/aa691172(VS.71).aspx
把这个改成
这个
Change this
to this