java中的异常处理(一)

今天在群里面,有人问关于异常的问题,当时瞬间空白了。基础不好啊!于是又来学一学。

java中异常就是一个表示阻止执行正常进行的错误或者情况。如果异常没有被处理,那么程序将会非正常终止。

而异常处理的好处是能是当程序在有可能抛出异常的地方抛出异常时,程序不至于非正常终止,还有就是将检查错误冲处理错误分离开来

package TestForException;

import java.util.Scanner;

public class Quotient {
	public static void main(String[] args) {
		/*
		 * 类Scanner,位于java.util包中,这个Scanner的具体用法为
		 * Scanner in = new Scanner(System.in);。
		 * 通过new创建一个Scanner对象,Scanner需要传入一个System.in作为参数,
		 * 这个我们可以看作是Scanner通过其内部机制将System.in包装起来而实现数据的读取工作的。
		 * Scanner对象通过一系列的in.nextXxx();方法来读取相应的基本类型的数据,
		 * 通过in.hasNextXxx();方法来判断是否还有下一个数据。
		 */
		Scanner input = new Scanner(System.in);
		System.out.println("Please input two integers:");
		int number1=input.nextInt();
		int number2=input.nextInt();
		int number3;
		try{
			/*
			 * throw语句的执行称为抛出一个异常。throw语句类似于方法调用,相当于调用catch
			 * 但又不返回throw语句执行
			 */
			if(number2==0){
			throw new ArithmeticException("divisor cannot be zero");
			}
			number3=number1/number2;
			System.out.println(number3);
		}catch(ArithmeticException ex){
			System.out.println(ex);
		}
	}

}

package TestForException;

import java.util.Scanner;

public class Quotient {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Please input two integers:");
		int number1=input.nextInt();
		int number2=input.nextInt();
		
		try{
			int result=QuotientWithMethod.quotient(number1, number2);
			System.out.println(result);
		}catch(ArithmeticException ex){//处理被调用方法的异常,实现异常处理
			System.out.println(ex);
		}
	}
}



package TestForException;

public class QuotientWithMethod {
	public static int quotient(int num1, int num2) {
		if(num2==0)
			throw new ArithmeticException("Divisor cannot be zero" );
		//抛出一个异常给调用者,而异常由调用者处理,这就是为什么很多库方法在出错的情况下都有调用者处理,
		//此处实现的是错误检查
		return num1/num2;
		}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值