java之异常处理

异常Exception我们分为
|--RuntimeException运行期异常,我们需要修正代码

|--非RuntimeException 编译期异常,必须处理的,否则程序编译不通过

异常有两种处理方式:

1、try...catch...finally
自己在catch处编写处理代码,后面的程序可以继续执行,即运行了catch里面的还会运行后面的代码

public class Test {
	public static void main(String[] args) {
		new Info().run();
	}

}

class Info {
	public void run(){
		int a = 1;
		int b = 0;
		try {
			int c = a/b;
		} catch (Exception e) {
			System.out.println("除零");
		}
		System.out.println("1111111");
	}
}

结果为:

除零
1111111

自己在catch处编写处理代码,后面的程序可以继续执行,即运行了catch里面的还会运行后面的代码

2、throw    抛出
把自己处理不了的,在方法上声明,告诉调用者,这里有问题,在catch中抛出异常,那么程序后面的代码就不会执行了。

public class Test {
	public static void main(String[] args) {
		int a = new Scanner(System.in).nextInt();
		try {
			new Info().score(a);
		} catch (CustomException e) {
			System.out.println(e.getMessage());
		}
		System.out.println("222222");

	}

}

class Info {
	public void score(int a) throws CustomException {
		if (a < 0 || a > 100) {
			throw new CustomException("成绩不合法")
		} else {
			System.out.println("成绩ok!");
		}
		System.out.println("111111");
	}
}
输出为:

-1
成绩不合法
222222

即在抛出后,有异常的方法就不会往后执行了,而是直接跳到调用者那里catch执行,因为catch那里没有抛出,而是打印异常(打印的内容和抛出时候时传入的参数内容一样)即执行完catch后代码会往后执行。

a、如果在catch中抛出的是运行时的异常(即这个异常继承自RuntimeException ),那么这个方法就不需要在后面throws这个异常










public void run() {
		int a = 1;
		int b = 0;
		int c;
		try {
			c = a / b;
		} catch (ArithmeticException e) {
			throw new ArithmeticException("除零异常");
		}
		System.out.println(c);
	}


b、如果在catch中抛出的是编译时的异常(即这个异常继承自Exception),那么这个方法就需要在后面throws这个异常

public void score(int a)throws CustomException {
		if (a < 0 || a > 100) {
			throw new CustomException("成绩不合法");
		} else {
			System.out.println("成绩ok!");
		}
	}


c、在自定义异常时,我们可以继承RuntimeException 或Exception,再写两个构造方法,空和参数为String的构造,再抛出给调用者处理

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值