我花了一些时间通过我在本科生中使用的教科书重新学习Java。在他们对例外的解释的尾端,他们提出以下代码:
public class ReadingObjects {
public static void main(String[] args) {
try{
FileInputStream fis = new FileInputStream("objects");
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while(true){
Auto temp = (Auto)ois.readObject();
System.out.println(temp);
}
}
catch(EOFException eofe){
System.out.println("End of file has been reached.");
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}
finally{
System.out.println("Closing file. . .");
ois.close();
}
}
catch(FileNotFoundException fnfe){
System.out.println("Unable to find the objects file.");
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
本书使用两个try/catch
块的原因是因为EOFException
类无法检查是否还有其他对象,程序将抛出ObjectInputStream
该文件(它没有hasNext()
类提供的等效于Scanner
的文件。此外,一旦抛出异常,将忽略在生成异常的try
中的点之后编写的任何代码;对于有问题的异常,Java将直接转到catch
块。因此,内部try/catch
块处理EOFException
,然后跳转到finally
部分。外部try
块处理任何剩余的异常。
我的主要问题是为什么要使用2 try/catch
块?这似乎是一个过于复杂的解决方案。为了确保我对此有正确的理解,我继续编写了以下代码,该代码只使用了一个try/catch
块:
public class ReadingObjects {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("objects");
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while(true){
Auto temp = (Auto)ois.readObject();
System.out.println(temp);
}
}
catch(EOFException eofe){
System.out.println("End of file has been reached.");
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}
catch(FileNotFoundException fnfe){
System.out.println("Unable to find the objects file.");
}
catch(IOException ioe){
ioe.printStackTrace();
}
finally{
System.out.println("Closing file. . .");
ois.close();
}
}
}
使用第二个解决方案,我仍然可以获得与第一个(书籍)解决方案相同的输出。这样做有什么保留吗?我应该警惕在我的main
方法中添加throws声明吗?
对此的任何澄清和意见将不胜感激。
答案 0 :(得分:0)
这是处理异常的两种不同技术。在第一个代码中,您正在使用嵌套的try catch块,有时可能会出现块的一部分可能导致一个错误并且整个块本身可能导致另一个错误的情况。在这种情况下,必须嵌套异常处理程序。
在第二个代码中,您正在尝试使用多个catch块。两者都是相同的输出,但这两种技术仅用于处理异常。
答案 1 :(得分:0)
ois.close()
也可能抛出异常。它将在第一个实现中优雅地处理,但在第二个实现中冒泡......
答案 2 :(得分:0)
这本书的解释并不成立。 package myPackage;
class inheritance {
int salary = 50000;}
public class worker extends inheritance {
int bonus = 10000;
public static void main(String[] args) {
worker obj1 = new worker();
System.out.println("employee salary is" + obj1.salary);
System.out.println("employee bonus is" + obj1.bonus);
}
}
和EOFException
可以很容易地在外层捕获。真正的区别在于,如果ClassNotFoundException
在 while循环中被捕获,那么你可以继续读取你可能拥有.class文件的其他对象。但是,该异常确实表明存在部署问题,因此继续读取流可能没有多大意义。