java异常
Throwable exception; //类
Exception exce; //继承Throwable
Error err; //继承Throwable
RuntimeException re; //继承Exception, 运行时异常
//Exception与Error 虚拟机是如何处理的?
//throw new Error(); //程序中止
//throw new Exception();
//必须try..catch或者throw, 程序可以继续执行, 编译时检查
//运行时检查, 不需要捕获, 运行时如果发生这类异常,程序中止
//throw new RuntimeException();
/*
异常分为运行时异常和检查异常,除了RuntimeException, 其它的都是CheckedException.
运行时异常包括:
Java.lang.ArithmeticException
Java.lang.ArrayStoreExcetpion
Java.lang.ClassCastException
Java.lang.IndexOutOfBoundsException
Java.lang.NullPointerException
检查异常包括:
Java.lang.ClassNotFoundException
Java.lang.NoSuchMetodException
java.io.IOException
Error包括:
OutOfMemoryError
*Error
异常可以被程序处理,错误无法处理。
自定义异常:只需要继承Exception
*/
System.out.println("dd");
try{
//运行时检查, 不需要捕获,如果捕获,程序继续执行
throw new RuntimeException();
}catch(Exception e){
;
}
System.out.println("xx");
异常示例:
testEx方法没捕获抛出的异常?
《Thinking in Java》书中提到,finally语句块中如果重新抛出异常,会覆盖掉之前try块中捕获的异常,finally块中使用return会丢失try块中捕获的异常,当然finally块中,不能同时出现抛出异常和return语句
public class TestException {
public TestException() {
}
boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}
boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
} catch (Exception e) {
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}
boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx2, finally; return value=" + ret);
return ret;
}
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}