由于在File类中引用了./..类表示路径文件,在调用getParentFile()后编译通过,运行时提示:
Exception in thread "main" java.lang.NullPointerException ....
为此定义了一个自定义异常来明确异常类,准备再捕获后再做转换处理,发现自定义异常没有响应,何故?程序如下:import java.io.File;
import java.io.IOException;public class FileTest1{

public static void main(String[] args) throws IOException,PathExpressErr{
File file = new File(".");

try{
System.out.println("file.getParentFile().isDirectory()="+file.getParentFile().isDirectory());
System.out.println("file.getParentFile().isFile()="+file.getParentFile().isFile());
System.out.println("file.getParentFile().exist()="+file.getParentFile().exists());
throw new PathExpressErr();
}catch(PathExpressErr e){
e.getMessage();
}

}
}
class PathExpressErr extends Exception{

String[] pathname ; public PathExpressErr(){
pathname = new String[]{".",".."};
}

public String getMessage(){

String pathStr = "";

for (int i=0; i<pathname.length; i++){
pathStr = pathname[i]+"  "+pathStr;
}

return "表示为"+pathStr+"的路径不能被识别,请进行转换!";
   }
}

解决方案 »

  1.   

    file.getParentFile().isDirectory()这句已经抛出NullPointerException,后面的根本不会执行。throw的地方改到catch中 
       catch (Exception e) {
          throw new PathExpressErr();
        }
      

  2.   

    不解,我在api中都查了,发现两个方法中没有说明会抛出NullPointerException,怎么会抛出呢?
    另外有一个SecurityException异常,这个安全异常指在哪些情况下出现呢?对这个异常不解?
      

  3.   

    NullPointerException是Runtime Exception,不需要说明
    你应该先了解一下java的异常机制,如checked/unchecked exception
      

  4.   

    呵呵,前段时间看了异常没有深入体会:)
    刚才又看了一遍,又体会了一层,非常感谢kingfish
      

  5.   

    NullPointerException是Runtime Exception 是unchecked exception ,是不用catch的