java中checked exception和 unchecked异常之间的区别
时间:2020-02-23 14:34:04 来源:igfitidea点击:
在本教程中,我们将在Java中看到已检查异常和未检查异常之间的区别。
什么例外(异常)?
例外是不需要的情况或者条件,而执行程序。
如果我们不正确处理异常,可能会导致程序异常终止。
什么是已检查异常( checked exception)?
检查异常是在编译时检查的异常。
如果我们不处理它们,我们将获得编译错误。
让我们通过示例来理解:如果不处理检查的异常,我们将获得如下编译错误:
所以有两个选项两个解决了上面的编译错误。
使用尝试和catch块:我们可以在尝试块中放置错误代码,并在Catch块中捕获异常。
例子:
package org.arpit.theitroad;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CheckedExceptionMain {
public static void main(String args[]) {
FileInputStream fis = null;
try {
fis = new FileInputStream("sample.txt");
int c;
while ((c = fis.read()) != -1) {
System.out.print((char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
如我们所见,我们在Catch块中的尝试块和各种异常中都会出现错误易于代码。
使用抛出:我们可以使用revrows关键字来处理异常。
package org.arpit.theitroad;
import java.io.FileInputStream;
import java.io.IOException;
public class CheckedExceptionMain {
public static void main(String args[]) throws IOException {
FileInputStream fis = null;
fis = new FileInputStream("sample.txt");
int k;
while ((k = fis.read()) != -1) {
System.out.print((char) k);
}
fis.close();
}
}
正如我们所看到的,我们使用掷骰子关键字来处理异常。
什么是未经检查的异常?
未经检查的异常是在编译时未选中的异常。
如果我们不处理异常,Java将不会抱怨。
例子:
package org.arpit.theitroad;
public class NullPointerExceptionExample {
public static void main(String args[]){
String str=null;
System.out.println(str.trim());
}
}
运行上面的程序时,我们将得到以下异常:
Exception in thread "main" java.lang.NullPointerException at org.arpit.theitroad.NullPointerException示例 .main(NullPointerExceptionExample .java:7)
另一个例子:
package org.arpit.theitroad;
public class ArrayIndexOutOfBoundExceptionExample {
public static void main(String args[]){
String strArray[]={"Arpit","John","Martin"};
System.out.println(strArray[4]);
}
}
运行上面的程序时,我们将得到以下异常:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at org.arpit.theitroad.ArrayIndexOutOfBoundExceptionExample .main(ArrayIndexOutOfBoundExceptionExample .java:7)

