`
shifulong
  • 浏览: 56687 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java异常问题总结

    博客分类:
  • java
阅读更多
Throwable
    Exception
    RuntimeException  可以捕获,也可以不捕获(NullPointerException,ArrayIndexOutOfBoundException等)
非运行时异常      必须捕获,否则编译报错
    Error
    编译器不要求强制处理(如OutOfMemoryError)

throw throws的区别
throw代码中使用,抛出异常
throws声明方法时使用

public class Test {
	public Test() {
	}

	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) {

		String s = new String(new char[1 << 30]);

		Test test = new Test();
		try {
			test.testEx();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


如果你的答案是这个,那就错了
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false

上面的测试代码有 两个坑
1,i/0 会抛出一个运行时异常即RunntimeException,可以捕获也可以不捕获
2,testEx2 catch 中的 throw 相当于一个结束语句,在执行完finally语句块之后才会被执行
    but...finally中 已经 return结束 (或者 再次throw),catch 中的 throw不会执行 也就不会抛出异常,testEx1中也不会接收异常


正确的打印结果
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

最后附一张高清图片


  • 大小: 51 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics