2017-05-13 60 views
-2

我需要将结果看作boolean result:true。但是我需要以非常规方式来做到这一点。使用其他方法处理其他方法中的异常catch

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()); 
    } 
} 

例外只能在被捕获()方法。 DetermineIfBatteriesAreInstalled()确定IfFlashlightCanBeTurnedOn 必须标记为:throws IOException。

+0

目前尚不清楚你的问题是什么 –

+0

好简单地说,我需要正确编译DetermineIfFlashlightCanBeTurnedOn()方法,并使用on()方法捕获异常,以便在控制台中显示“true”。 – SpicyJam

回答

2

您可以使用try{}catch(){}代替:

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

我忘了只在告诉你们,我可以使用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?

+1

好点@BoristheSpider谢谢你我编辑它 –

+0

我忘了告诉你们我只能在on()方法中使用try/catch块 – SpicyJam

+0

检查我的编辑@SpicyJam –