今天在群里面,有人问关于异常的问题,当时瞬间空白了。基础不好啊!于是又来学一学。
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;
}
}