初学者:java练习题———含答案------异常处理(5)

在这里插入图片描述
在这里插入图片描述

public class MyExceptionTest {
	public static void main(String[] args) {
		try{
			int x = 68;
			int y = Integer.parseInt(args[0]);
			int z = x/y;
			System.out.println("x/y的值是:" + z);
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("缺少命令行参数。" + e);
		}catch(NumberFormatException e){
			System.out.println("参数类型不正确。" + e);
		}catch(ArithmeticException e){
			System.out.println("算数运算错误。" + e);
		}finally {
			System.out.println("程序执行完毕!" );
		}
	}
}

在这里插入图片描述
若出现这种为问题可以去查一看就会的

运行结果为
在这里插入图片描述
在这里插入图片描述

class MotorException extends Exception{
	public MotorException() {
		super();
		}
	public MotorException(String s) {
		super(s);
	}
}

class Car{
	private float speed = 0;
	private float MAX_V = 300;
	public void accelerate(float inc) throws MotorException{
		if(speed+inc > MAX_V) {
			throw new MotorException("发动机将被损坏!");
		}else {
			speed+=inc;
		}
	}
}

public class Test {
	public static Car car;
	public static void main(String args[]) {
		boolean isStart = true;
		car = new Car();
		while(isStart)
			try {
			car.accelerate(0.5f);
		}catch(MotorException me){
			System.out.println("Mechanical problem :" + me);
			isStart = false;
		}
	}
}

运行结果为
在这里插入图片描述
在这里插入图片描述

public class Test {

	public static void main(String[] args) {
		float inputFloat;
		double resultFloat;
		try {
			inputFloat = Float.parseFloat(args[0]);
			if (inputFloat < 0.0f) {
				System.out.println("输入参数小于零,不能求平方根,程序结束!");
				System.exit(0);
			}
			resultFloat = Math.sqrt(inputFloat);
			System.out.println(inputFloat + " 的平方根是:" + resultFloat);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("运行错误:数组下标越界!");
		} catch (NullPointerException e) {
			System.out.println("运行错误:参数字符串为空,缺少参数!");
		} catch (NumberFormatException e) {
			System.out.println("运行错误:参数字符串非法,不能转换为浮点数!");
		} finally {
			System.out.println("程序执行完毕");
		}
	}
}

运行结果为
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走丢的男孩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值