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