关于java中的异常

一直不理解为什么要抛出异常、怎么throw、怎么cache,lab2稀里糊涂看着别人用照葫芦画瓢也用了,但是不明白内在逻辑,所以整理了一下。

首先是为什么要throw、cache异常?我看了好多资料后慢慢理解,其实就是当程序很长的时候,不希望出现一个问题,就停下debug然后再次开始运行,这很耗费心血,所以初期学C语言的时候,我们往往会printf一堆东西,就是在告诉程序,“要是出错了你别停下,你print一下,我就知道哪里有问题了”,但是这个太愚蠢了,而且事后删print语句也很麻烦,所以有了try-cache异常(写到这突然想起来,老师上课好像说过类似的话,那时候没理解😓)。

然后就是为啥要throw,这个我感觉和java的OOP有关,由于OOP,所以会导致很多方法的嵌套,而throw就是帅锅,把这个“异常”你想要谁解决,就甩到哪一层,再cache。

弄明白为啥要有抛出异常、捕获异常,接下来就是,哪些异常是需要我cache的呢?

java中Error、RuntimeException是不需要cache的,换句话说,就是cache了也没用,因为他们基本上是cache了也做不了什么的,这类基本上java会cache;而非运行时异常是需要抛出和捕获的。

还有一个try-cache和try-cache-final:

对于try-catch-finally语句:先执行try 块中的代码,如果正常运行没有发生异常则执行完后执行finally 代码块中的代码;如若在try 中发生异常且被catch 捕捉到则执行catch 中的代码块,然后执行finally 块中的代码。

有一个被好多文章引用的经典例子,我也引用一下,弄明白这个代码就是差不多明白了这俩的区别。

package Exception;
 
public class exception4 {
	public exception4() {
	}
 
	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) {
		exception4 testException1 = new exception4();
		try {
			testException1.testEx();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

正解:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值