有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java尝试捕获(IOG异常)错误

如果我试图捕获一个IOException,就会得到错误exception java.io.IOException is never thrown in body of corresponding try statement。但是如果我改用Exception,错误就消失了。 有人能描述一下为什么会发生这种情况吗

public class CmndLine {
    public static void main(String args[]) {
        int i, j = 0;
        long m, l;
        boolean b1 = false;
        String str = "";
        String [] s;

        for (i = 0; i < args.length; i++)
            str += args[i];

        File file = new File(str);

        try {
            b1 = file.exists();
            System.out.println(b1);

            if (b1 == true) {
                m = file.lastModified();
                l = file.length();
                s = file.list();
                java.util.Date d = new java.util.Date(m);
                System.out.println("Name : " + file.getName());
                System.out.println("Parent : " + file.getParent());
                System.out.println("Path : " + file.getPath());
                System.out.println("Date and Time of Modification : " + d);
                System.out.println("Size : " + l + " Bytes");
                boolean c = file.isDirectory();

                if (c == true) {
                    System.out.println("");
                    for (String t : s)       
                        System.out.println(t);
                }
            }
        }
        catch (IOException g) {
            g.printStackTrace();
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    try块中没有可以抛出IOException的命令。因此,您永远不会捕捉到一个,而您的IDE/编译器正告诉您这一点

    如果您改为编写catch(Exception e),您将捕获任何可能的Exception,如File.exists()File.lastModified()File.length()等方法可以抛出的SecurityException

    因此,尝试改用catch(SecurityException e),并为您想要捕获的任何特定Exception类型添加额外的catch

  2. # 2 楼答案

    try块中使用的任何方法都没有声明它们抛出类型为IOException的已检查异常,因此您不能catch

    因为Exception包含检查和未检查的异常,所以它不会给您带来相同的问题