通过throws抛出异常时,针对可能出现的多种异常情况,有以下两种解决方案:
方案一:throws后面接多个异常类型,中间用逗号分隔
package java_exception;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TryDemoThree {
/**
* 通过throws抛出异常时,针对可能出现的多种异常情况,解决方案:
* 1.throws后面接多个异常类型,中间用逗号分隔
*/
public static int test() throws ArithmeticException, InputMismatchException {
Scanner input = new Scanner(System.in);
System.out.println("=====运算开始=====");
System.out.print("请输入第一个整数:");
int one = input.nextInt();
System.out.print("请输入第二个整数:");
int two = input.nextInt();
System.out.println("=====运算结束=====");
return one/two;
}
public static void main(String[] args) {
// TryDemoTwo t = new TryDemoTwo();
try{
int result = test();
System.out.println("one和two的商是:" + result);
}catch(ArithmeticException e){
System.out.println("除数不能为0!");
e.printStackTrace();
}catch(InputMismatchException e){
System.out.println("请输入整数!");
e.printStackTrace();
}catch(Exception e){
}
}
}
方案二:
package java_exception;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TryDemoThree {
/**
* 通过throws抛出异常时,针对可能出现的多种异常情况,解决方案:
* 1.throws后面接多个异常类型,中间用逗号分隔
* 2.throws后面接Exception
*/
/**
* 测试接收数据相除结果的方法
* @return 两个接收数据的商
* @throws ArithmeticException
* @throws InputMismatchException
*/
// public static int test() throws ArithmeticException, InputMismatchException {
// Scanner input = new Scanner(System.in);
// System.out.println("=====运算开始=====");
// System.out.print("请输入第一个整数:");
// int one = input.nextInt();
// System.out.print("请输入第二个整数:");
// int two = input.nextInt();
// System.out.println("=====运算结束=====");
// return one/two;
// }
public static int test() throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("=====运算开始=====");
System.out.print("请输入第一个整数:");
int one = input.nextInt();
System.out.print("请输入第二个整数:");
int two = input.nextInt();
System.out.println("=====运算结束=====");
return one/two;
}
public static void main(String[] args) {
// TryDemoTwo t = new TryDemoTwo();
try{
int result = test();
System.out.println("one和two的商是:" + result);
}catch(ArithmeticException e){
System.out.println("除数不能为0!");
e.printStackTrace();
}catch(InputMismatchException e){
System.out.println("请输入整数!");
e.printStackTrace();
}catch(Exception e){
}
}
}
当抛出的是Exception(异常的父类)时,在try-catch结构中可以不写具体会出现哪种类型的异常,但必须写Exception,即:
try{
int result = test();
System.out.println("one和two的商是:" + result);
}catch(Exception e){
}
是可以的。
但:
try{
int result = test();
System.out.println("one和two的商是:" + result);
}catch(ArithmeticException e){
System.out.println("除数不能为0!");
e.printStackTrace();
}catch(InputMismatchException e){
System.out.println("请输入整数!");
e.printStackTrace();
}
不可以。