JAVA 语言如何进行异常处理,关键字:throws,throw,try,catch,finally 分 别代表什么意义?在 try 块中可以抛出异常吗?

1.throws 捕获并向外抛出异常

package 拓展作业;
public class Test2 {
	public static void main(String[] args) throws Exception {
		int result = divide(4, 0);
		System.out.println(result);
	}
	public static int divide(int x, int y) throws Exception {
		int result = x / y;
		return result;
	}
}

如此向外抛出会直接抛出异常信息
结果:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at 拓展作业.Test2.divide(Test2.java:10)
	at 拓展作业.Test2.main(Test2.java:5)

2.try,catch是内部捕获异常并做自定义处理

package 拓展作业;

public class Test2 {
	public static void main(String[] args) {
		int result;
		try {
			result = divide(4, 0);
			System.out.println(result);
		} catch (Exception e) {

			System.out.println("除数为0错误");//自定义处理方式

		}

	}

	public static int divide(int x, int y) throws Exception {
		int result = x / y;
		return result;
	}
}

结果:

除数为0错误

3.finally 是无论是否有异常都会被处理的语句,除非在 finally 前存在被执行的
(在最后必须进行的处理,做收尾工作)

4.throw 抛出异常

package 拓展作业;

public class Test2 {

	public static void main(String[] args) {
		String s = "abc";
		if (s.equals("abc")) {
			throw new NumSameException("字符相同");
		} else {
			System.out.println(s);
		}
	}

}

class NumSameException extends NumberFormatException {

	public NumSameException() {
		super();

	}

	public NumSameException(String s) {
		super(s);

	}

}

结果:

Exception in thread "main" 拓展作业.NumSameException: 字符相同
	at 拓展作业.Test2.main(Test2.java:8)

throw是语句抛出一个异常。
语法:throw 异常对象;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值