使用其他方法catch处理其他方法中的异常

时间:2017-05-13 09:16:56

标签: java exception

我需要将结果视为boolean结果:true。但是我需要以非普通的方式做到这一点。

import java.io.IOException;

public class FlashLight {

    private Bulb bulb;
    private Battery[] batteries;

    public void on() {
        try {

            if (this.IsThereEnoughPower()) {

                this.bulb.setOn(true);

                for (Battery b : batteries) {
                    b.setPower(b.getPower() - this.bulb.getBrightness());
                }
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());

            this.setBatteries(new Battery[4]);

        }
    }

我需要在方法on()中捕获异常,但我只能修改方法:DetermineIfFlashlightCanBeTurnedOn

    public boolean DetermineIfFlashlightCanBeTurnedOn() throws IOException {

        return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
    }

    private boolean DetermineIfBatteriesAreInstalled() throws IOException {
        if (batteries.length < 4) {
            throw new IOException(Math.abs(-4 + batteries.length));
        }
        for (Battery b : batteries) {
            if (b == null) {
                return false;
            }
        }

        return true;
    }

    private boolean IsThereEnoughPower() {
        for (Battery b : batteries) {
            if (b.getPower() < MIN_BATTERY_POWER) {
                return false;
            }
        }

        return true;
    }

    private static void testLatarki(String... args) {

        FlashLight flashlight = new Flashlight();
        System.out.println(flashlight.DetermineIfFlashlightCanBeTurnedOn());
    }
}
  

只能在on()方法中捕获异常。   DetermineIfBatteriesAreInstalled()DeterminIfFlashlightCanBeTurnedOn   必须签名为:抛出IOException。

1 个答案:

答案 0 :(得分:2)

您可以改为使用try{}catch(){}

public boolean DetermineIfFlashlightCanBeTurnedOn() {
    try {
        return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
    } catch (Exception e) {
        //log your exception
    }
    return false;
}
  

我忘了告诉大家我只能在on()中使用try / catch块   方法

在这种情况下,您可以使用RuntimeException在您的方法中不需要使用throws IOException

if (batteries.length < 4) {
    throw new RuntimeException(Math.abs(-4 + batteries.length)+"");
}

所以:

public boolean DetermineIfFlashlightCanBeTurnedOn() {
//--not need to use throw throws IOException-------^ 
    return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
}

private boolean DetermineIfBatteriesAreInstalled() {
//--not need to use throw throws IOException------^ 
    if (batteries.length < 4) {
        throw new RuntimeException(Math.abs(-4 + batteries.length) + "");
        //----------^^ 
    }
    for (Battery b : batteries) {
        if (b == null) {
            return false;
        }
    }

    return true;
}

您可以在此处阅读更多内容Is there a way to throw an exception without adding the throws declaration?