在java世界中有两种异常,一种Checked Exceptions
,另一种叫Unchecked Exceptions.
1) Checked Exceptions :
Checked exceptions就是在编译的时候(during compile time)就被检查到了。如果有异常就会不通过。所以Checked exceptions也被叫做compile time exceptions。
这些异常我们必须要使用try-catch去handle它们或者用“throws”这个句式把它抛到上一层去。如果你不去handle它,那么它们就会在compile的时候向你抛出compile time error,自然就无法compile通过了。java.lang.Exception底下除去RunTimeException下的所有sub class都是checked exceptions。
下面这个例子throws了一个checked exception。但是由于没有去handle,所以在compile的时候就抛出了compile time error。
public class CheckedException { public static void main(String[] args) { Class.forName("AnyClassName"); //Compile time error because //above statement throws ClassNotFoundException which is a checked exception //this statement must be enclosed within try-catch block or declare main method with throws clause } }
ps:在java ide里,默认会提示这些checked exception,所以你一般都会把它们handle掉。
下面这段代码是正确的做法:
public class CheckedException { public static void main(String[] args) { try { Class.forName("AnyClassName"); } catch (ClassNotFoundException ex) { System.out.println("ClassNotFoundException will be caught here"); } } }
或者
public class CheckedException { public static void main(String[] args) throws ClassNotFoundException { Class.forName("AnyClassName"); } }
2) Unchecked Exceptions :
Unchecked exceptions就是一种只有在runtime的时候才会发生的异常。它们不能在compile time的时候就被发现,因为它们只有program运行了以后才会出现。所以Unchecked exceptions也被叫做:Run Time Exceptions。
RunTimeException低下所有的sub class以及Error低下所有的sub class都是unchecked exceptions。
如果在你的program中的任何一个语句(statement)抛出了unchecked exceptions并且你没有用try-catch或者“throws”去handle它们,那么它们并不会在compile的时候抛出compile time error。你会成功的通过编译。一切看起来很安静。但,当runtime的时候,程序跑起来的时候,当执行来到了有问题的那一行的时候,program 就会出现问题。
所以,为了避免program的过早的中断,我们也必须去handle这些在runtime时候可能出现的异常。比如下面这个例子:
public class UncheckedException { public static void main(String[] args) { int i = Integer.parseInt("Unchecked Exception"); //Above statement throws NumberFormatException which is an unchecked exception } }
上面这个program在runtime的时候抛出了一个NumberFormatException。我们没有去handle,所以就会在runtime的时候出现问题。为了避免这种情况,我们就必须在code的时候,通过人脑判断之后,在这里加入try-catch的block。
tips:在你code的时候,不仅仅要去处理那些checked exception使得编译通过,同时还要去用你的知识积累去判断那些可能存在的潜在的unchecked exception并去处理它们。如果说处理checked exception仅仅是为了编译通过,那么处理unchecked exception则会让你的程序更加的健壮。这是两个不同层次的思考。
以下是推荐的做法:
public class UncheckedException { public static void main(String[] args) { try { int i = Integer.parseInt("Unchecked Exception"); //Above statement throws NumberFormatException which is an unchecked exception } catch (NumberFormatException e) { System.out.println("NumberFormatException will be caught here"); } } }
Checked 和 Unchecked Exceptions之间的区别
下面这个图向你展示了在exceptions的体系里
哪些是checked exceptions ,哪些是 unchecked exceptions。