

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("程序执行完毕");
}
}
}
运行结果为


示例代码展示了如何处理不同类型的异常,包括数组越界、数字格式错误和算术运算异常。程序通过try-catch-finally结构确保了在执行过程中能够捕获并处理错误,同时在finally块中显示程序执行完毕的信息。此外,还展示了一个自定义异常`MotorException`在汽车加速场景中的应用,当速度超过最大值时抛出。最后,一个示例演示了从命令行参数中获取浮点数并计算平方根的过程,同时处理了参数缺失、类型错误和数值负数的情况。

被折叠的 条评论
为什么被折叠?



