例如:
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
投掷之外的工作方式.
我一直在看代码,我已经看过尝试资源.之前我使用过标准的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)