获取错误:FileNotFoundException的无法访问的catch块。永远不会从try语句主体抛出此异常

时间:2017-04-08 20:54:40

标签: java

每当我点击具有特定图像名称的网址时,我已经写了一段用于返回图像的代码,如果找不到图像,则只返回错误图像。

@GET
@Path("/getImage/{param1}")
@Produces({ "image/png", "image/jpeg", "image/gif", "image/jpg" })
public Response getProductimage(@PathParam("param1") String recievedData) {


    File file = null;
    try {
        file = new File("C:/Users/Gaurav/Desktop/AppData/"
                + recievedData);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        file = new File("C:/Users/Gaurav/Desktop/AppData/error.png");

        System.out.println(e.getMessage());
    }

    return Response.ok(file).build();

}

在尝试查找错误图像时,我仍然收到此错误

SEVERE: Servlet.service() for servlet [Jersey RESTful Application] in context with path [/WebServices] threw exception [org.glassfish.jersey.server.ContainerException: java.io.FileNotFoundException: C:\Users\Gaurav\Desktop\AppData\average11.png (The system cannot find the file specified)] with root cause
java.io.FileNotFoundException: C:\Users\Gaurav\Desktop\AppData\average.png15 (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:131)
    at org.glassfish.jersey.message.internal.FileProvider.writeTo(FileProvider.java:115)

代码中有什么问题?

1 个答案:

答案 0 :(得分:3)

调用new File("X:/non/existing/file")抛出任何异常,因此永远不会执行catch块。

您应该use .exists()检查文件是否存在,或者更好,.canRead()以检查您是否真的可以阅读它。

File file = new File("C:/Users/Gaurav/Desktop/AppData", recievedData);
if (!file.canRead()) {
    file = new File("C:/Users/Gaurav/Desktop/AppData/error.png");
}
return Response.ok(file).build();