1 package mycodes.exception.test2;
2 /*
3 * 本类用数组模拟栈内存(方式2:未控制下标),通过异常处理提示栈满栈空
4 */
5 public class Stack2 {
6 private String[] arr;
7 private int p = -1;
8
9 public Stack2(int max) {
10 arr = new String[max];
11 }
12
13 public void push(String str) throws StackException {
14 try {
15 p++;
16 arr[p] = str;
17 } catch (ArrayIndexOutOfBoundsException e) {
18 p--; //在这里加此代码是解决“栈满时进行弹栈操作提示栈空”问题的最优方式,
19 //要知道catch块中的代码就是“专门用来处理异常”的,
20 //p-- 在本方法中处理掉数组索引越界异常,防止弹栈出错
21 throw new StackException("栈满了,无法继续压栈", e);
22 }
23 }
24
25 public String pop() throws StackException {
26 try {
27 //栈满后若不做任何处理直接弹栈会因数组越界直接提示“栈空”,发生异常,无法实现弹栈功能
28 //而把 p--; 调整到第一行虽然能实现栈满时弹栈正常,但是若栈有元素但是不满则会造成漏掉栈顶元素,违反了栈先进后出的原则
29 // 在这里加判断语句可以实现正常弹栈功能,但是不是最优的办法
30 // if(p == arr.length) p --;
31
32 String str = arr[p];
33 arr[p] = null;
34 p--;
35 return str;
36 } catch (ArrayIndexOutOfBoundsException e) {
37 throw new StackException("栈空,无法继续弹栈", e);
38 }
39 }
40 }
1 package mycodes.exception.test2;
2
3 public class StackException extends Exception {
4
5 public StackException(){}
6 public StackException(String msg){
7 super(msg);
8 }
9 public StackException(String msg,Throwable e){
10 super(msg,e);
11 }
12 }
1 package mycodes.exception.test2;
2 /*
3 * 本类用于测试 通过数组模拟栈内存的类 Stack2
4 */
5 public class TestStack2 {
6
7 /**
8 * @param args
9 */
10 public static void main(String[] args) {
11 Stack2 s = new Stack2(10);
12 //压栈
13 try {
14 for(int i = 1;i<9;i++){
15 s.push("abc"+i);
16 }
17 } catch (StackException e) {
18 e.printStackTrace();
19 }
20 // 弹栈
21 try {
22 for(int i = 0;i<14;i++){
23 String str =s.pop();
24 System.out.println("弹栈-->" +str );
25 }
26 } catch (StackException e) {
27 e.printStackTrace();
28 }
29 }
30 }