Java进阶教程之异常处理(2)
public class Test { public static void main(String[] args) { Battery aBattery = new Battery(); aBattery.chargeBattery(0.5); aBattery.useBattery(-0.5); } } class Battery { /** * increase battery */ public void chargeBattery(double p) { // power <= 1 if (this.power + p < 1.) { this.power = this.power + p; } else { this.power = 1.; } } /** * consume battery */ public boolean useBattery(double p) { try { test(p); } catch(Exception e) { System.out.println("catch Exception"); System.out.println(e.getMessage()); p = 0.0; } if (this.power >= p) { this.power = this.power - p; return true; } else { this.power = 0.0; return false; } } /** * test usage */ private void test(double p) throws Exception // I just throw, don't handle { if (p < 0) { Exception e = new Exception("p must be positive"); throw e; } } private double power = 0.0; // percentage of battery }
useBattery()表示使用电池操作。useBattery()方法中有一个参数,表示使用的电量。我们使用test()方法测试该参数。如果该参数为负数,那么我们认为有异常,并抛出。
在test中,当有异常发生时(p < 0),我们创建一个Exception对象e,并用一个字符串作为参数。字符串中包含有异常相关的信息,该参数不是必需的。使用throw将该Exception对象抛出。
我们在useBattery()中有异常处理器。由于test()方法不直接处理它产生的异常,而是将该异常抛给上层的useBattery(),所以在test()的定义中,我们需要throws Exception来说明。
(假设异常处理器并不是位于useBattery()中,而是在更上层的main()方法中,我们也要在useBattery()的定义中增加throws Exception。)
在catch中,我们使用getMessage()方法提取其异常中包含的信息。上述程序的运行结果如下:
catch Exception p must be positive
异常处理器中,我们会捕捉任意Exception类或者其衍生类异常。这往往不利于我们识别问题,特别是一段程序可能抛出多种异常时。我们可以提供一个更加具体的类来捕捉。
自定义异常
我们可以通过继承来创建新的异常类。在继承时,我们往往需要重写构造方法。异常有两个构造方法,一个没有参数,一个有一个String参数。比如:
class BatteryUsageException extends Exception { public BatteryUsageException() {} public BatteryUsageException(String msg) { super(msg); } }
我们可以在衍生类中提供更多异常相关的方法和信息。
在自定义异常时,要小心选择所继承的基类。一个更具体的类要包含更多的异常信息,比如IOException相对于Exception。
总结
异常处理是在解决问题,同时也是在制造问题。大型项目中,过多、过细的异常处理往往会导致程序变得一团糟。异常处理的设计并不简单,并需要谨慎使用。
- 上一篇:Java进阶教程之IO基础
- 下一篇:Java进阶教程之String类