try-catch 异常练习 
思路
- 创建Scanner对象
- 使用无限循环,去接收一个输入
- 将该输入的值,转成一个Int
- 如果在转换时,抛出异常,则说明输入的内容不是一个可以转成Int的内容
- 如果没有抛出异常, 则break该循环
eclipse中try-catch:选中可能有异常的语句,右键–surround with
代码
public class A01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = 0;
while(true){
System.out.println("请输入一个整数");
try {
num = Integer.parseInt(sc.next());
break;//没有异常,退出
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("你输入的不是一个整数");
}//转换成为Int(有可能异常,输入的是hello)
}
System.out.println("你输入的值是:" + num);
sc.close();
}
}
自定义异常(throw)
思路
- 定义类继承Exception(变成编译时异常)或RuntimeException(变成运行时异常)
- 通过构造器,设置信息
代码
public class A02 {
public static void main(String[] args) {
int age = 23;
if(!(age >= 18 && age <= 120)){
<mark>throw</mark> new AgeException(“年龄需要在18-120之间”);
}
System.out.println(“你的年龄是:” + age);
}
}
class AgeException extends RuntimeException{
public AgeException(String message){//构造器
super(message);
}
}
public class A03 {
public static double cal(int n1, int n2){
return n1 / n2;
}
public static void main(String[] args) {
try {
//验证输入的参数个数是否正确 两个
if(args.length != 2){
throw new ArrayIndexOutOfBoundsException("参数个数不对");
}
//把接收到的参数,转成整数[可能输入的是字符串]
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
double result = cal(n1,n2);//该方法可能抛出除零异常
System.out.println("计算结果为:" + result);
}
catch (ArrayIndexOutOfBoundsException e) {
//参数个数是否为两个(下标越界异常)
System.out.println(e.getMessage());
}
catch (NumberFormatException e){
//数据格式异常
System.out.println("参数格式不正确,需要输入整数");
}
catch (ArithmeticException e){
System.out.println("出现了除零的异常");
}
}
}
idea参数配置
Eclipse参数设置
(右键要运行的类 ——> Run AS——> Run Configurations…——> Arguments——> )