如何只在main中捕获异常?

时间:2014-11-26 17:07:33

标签: java exception

我有一个文件,我将在另一个类中打开。在我对该文件的操作中,我将需要例外。我如何只在主要处理它们并且只是抛出它们?请给我我一直在尝试的语法2天,我没有得到的想法。每次我打开文件夹,我需要尝试捕获并在该功能中捕获它,我想在主要捕获它。

1 个答案:

答案 0 :(得分:1)

您可以将异常抛出到其他类中,并使用try catch块在main方法中捕获该异常。

import java.io.*;  
class SearchFiles{  
 void method()throws FileNotFoundException{  
  throw new FileNotFoundException("file not found");  
 }  
}  


public class ThrowsTest{  
   public static void main(String args[]){  
    try{  
     ThrowsTest t=new ThrowsTest();  
     t.method();  
    }catch(Exception e){System.out.println("exception handled");}     

    System.out.println("normal flow...");  
  }  
}