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();
}
}
}
# 1 楼答案
在
try
块中没有可以抛出IOException
的命令。因此,您永远不会捕捉到一个,而您的IDE/编译器正告诉您这一点如果您改为编写
catch(Exception e)
,您将捕获任何可能的Exception
,如File.exists()
、File.lastModified()
和File.length()
等方法可以抛出的SecurityException
因此,尝试改用
catch(SecurityException e)
,并为您想要捕获的任何特定Exception
类型添加额外的catch
块# 2 楼答案
在
try
块中使用的任何方法都没有声明它们抛出类型为IOException
的已检查异常,因此您不能catch
它因为
Exception
包含检查和未检查的异常,所以它不会给您带来相同的问题