相关疑难解决方法(0)

为什么Try/Catch块会创建新的变量范围?

例如:

try
{
    SomeObject someObject = new SomeObject();
    someObject.dangerousMethod();
}
catch(Exception e)
{
}
someObject.anotherMethod(); //can't access someObject!
Run Code Online (Sandbox Code Playgroud)

但你可以在try/catch块之前声明它然后它工作正常:

SomeObject someObject;
try
{
    someObject = new SomeObject();
    someObject.dangerousMethod();
}
catch(Exception e)
{
}
someObject.anotherMethod(); //works fine
Run Code Online (Sandbox Code Playgroud)

我只是想知道这个的设计原因.为什么在try/catch块内创建的对象不在方法的其余部分范围内?也许我不会深入了解try/catch除了观看Exceptions投掷之外的工作方式.

java scope try-catch

44
推荐指数
4
解决办法
3万
查看次数

尝试使用资源与Try-Catch

我一直在看代码,我已经看过尝试资源.之前我使用过标准的try-catch语句,看起来它们做同样的事情.所以我的问题是Try With Resources vs Try-Catch 它们之间有什么区别,哪个更好.

这是资源的尝试:

objects jar = new objects("brand");
objects can= new objects("brand");

try (FileOutputStream outStream = new FileOutputStream("people.bin")){
    ObjectOutputStream stream = new ObjectOutputStream(outStream);

    stream.writeObject(jar);
    stream.writeObject(can);

    stream.close();
} catch(FileNotFoundException e) {
    System.out.println("sorry it didn't work out");
} catch(IOException f) {
    System.out.println("sorry it didn't work out");
}
Run Code Online (Sandbox Code Playgroud)

java try-catch try-with-resources

31
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×2

try-catch ×2

scope ×1

try-with-resources ×1