Java 异常: 编译时和运行时异常

Throwable 类是所有异常类的父类



RuntimeException 继承自 Throwable



在 JDK 文档里面




中文意思如下:





之前,写代码的时候 throw 某个异常,

发现有些异常就是不需要 throws 语句(在方法声明后面),而有些必须加上 throws 语句在方法声明后面)

或者 try..catch(在方法体里面)。


具体可以参见帖子:http://bbs.csdn.net/topics/390279427


看一个小例子

接收控制台输入的 两个 int 类型数,然后将两者相除。

package it.mark;

import java.util.Scanner;

public class OnExceptionDemo {

	public static void main(String[] args) {
		usingDivisionCalcu();
	}

	/**
	 * 使用除法计算器计算数值.
	 */
	private static void usingDivisionCalcu() {
		int[] input = new int[2];
		// 创建 Scanner 对象
		Scanner scan = new Scanner(System.in);
		// 等待用户输入
		while (scan.hasNextInt()) {
			for (int i = 0; i < 2; i++) {
				input[i] = scan.nextInt();
			}

			break;
		}

		// 从用户输入数据中,获取被除数和除数
		int dividend = input[0];
		int divisor = input[1];
		calc4division(dividend, divisor);
	}

	/**
	 * 除法計算.
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 */
	private static void calc4division(int dividend, int divisor) {
		int result = 0;
		result = dividend / divisor;
		System.out.println("计算结果是: " + result);
	}

}



很明显,除数为 0 是错误的。


修改一下 calc4division 方法

/**
	 * 除法計算.
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 */
	private static void calc4division(int dividend, int divisor) {
		int result = 0;

		if (divisor == 0) {
			throw new ArithmeticException("除数是0,不符合人类计算规则!");
		}
		
		result = dividend / divisor;

		System.out.println("计算结果是: " + result);
	}



这里可以看出,在方法 calc4division 里面 throw ArithmeticException 异常,

但是编译器并没有要求我 throws 或者 try...catch


如果你换成 Exception 或者其子类,编译器就会要求你了。


这里,我们自己可以去直接捕获

/**
	 * 除法計算.
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 */
	private static void calc4division(int dividend, int divisor) {
		int result = 0;

		try {
			result = dividend / divisor;
		} catch (ArithmeticException ae) {
			System.out.println("除数是0,不符合人类计算规则!" + ae.getMessage());
		}

		System.out.println("计算结果是: " + result);
	}



最后提醒

如果你的代码里面出现关于 throw RuntimeException,那就要根据实际情况去处理了。

是捕获还是让他运行时报错,由您决定!



更多关于 try catch 可以 go ---> 

http://blog.csdn.net/androidbluetooth/article/details/7868521






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值