输入两个正整数并计算它们之和,当输入任意的一个数超出(0-10)范围时,抛出自己自定义的异常(NumberRangeException),异常的信息显示”数字不在指定范围。“
?
class="java" name="code">package MyException; class NumberRangeException extends Exception { public NumberRangeException() { super(); } public NumberRangeException(String msg) { super(msg); } }
?
package MyException; public class ExceptionTest { private static int TOTAL; public static void add(int x, int y) throws NumberRangeException { if( x > 10 || x < 0 ) { throw new NumberRangeException("数字不在指定范围"); } else if( y > 10 || y <0 ) { throw new NumberRangeException("数字不在指定范围"); } else { TOTAL = x + y; System.out.println(TOTAL); } } public static void main(String[] args) { try { add(7,9); } catch (NumberRangeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
?
?