1.1按照继承关系 分为Error和Exception
Error:大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。常见的有:StackOverflowError OutOfMemoryError
Exception:是程序本身可以处理的异常。太多了 不举例了 在Eclipse中 鼠标放在类名上 Ctrl+T 显示继承关系
RunTimeException:运行时的异常
Other:Exception和其子类中 除了RunTimeException以外的其余异常
1.2 按照是否在编译的时候做检查 可以分为unchecked exception和
unchecked exception:在编译的时候 不用检查的异常
checked exception:在编译的时候 检查的异常 必须cactch 不然无编译已通过
public class Main {
public static void main(String[] args) {
Main mMain = new Main();
try {
mMain.other();
} catch (Exception e ) {
// 必须catch 不然无法编译通过
}
// 无须catch 可以編譯運行通過
mMain.runtimeException();
mMain.error();
}
private void error() throws Error {
throw new Error("error" );
}
private void other() throws Exception {
throw new Exception("other");
}
private void runtimeException() throws RuntimeException {
throw new RuntimeException("runtimeException");
}
}
- 关于catch中有return finally中的代码如何执行
public class FinaliyTest {
static int i = 0;
int testExReturn() throws Exception {
try {
testEx1();
i++;
System.out.println("try i : " + i);
} catch (Exception e) {
i++;
System.out.println("catch i : " + i);
return i;
} finally {
i++;
System.out.println("finally i : " + i);
// case 1
return i;
}
// case 2
return i;
}
void testEx1() throws Exception {
throw new Exception();
}
public static void main(String[] args) {
FinaliyTest mFinaliyTest = new FinaliyTest();
try {
int k = mFinaliyTest.testExReturn();
System.out.println(k);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(i);
}
}
Case 1输出
catch i : 1
finally i : 2
2
2
Case 2 输出
catch i : 1
finally i : 2
1
2
总结:
1.finally中的代码始终会运行 即使catch中有return finally中的代码依旧会运行
2.如果finally中有return 则不会执行catch中return