在Java编程中,如何处理空堆栈异常?
本例展示了如何使用Date 类的System.currentTimeMillis() 方法和Stack 类的s.empty() ,s.pop() 方法来处理空堆栈异常。
package com.yiibai; import java.util.Date; import java.util.EmptyStackException; import java.util.Stack; public class EmptyStackExcept { public static void main(String[] args) { int count = 1000000; Stack s = new Stack(); System.out.println("Testing for empty stack"); long s1 = System.currentTimeMillis(); for (int i = 0; i <= count; i++) if (!s.empty()) s.pop(); long s2 = System.currentTimeMillis(); System.out.println((s2 - s1) + " milliseconds"); System.out.println("Catching EmptyStackException"); s1 = System.currentTimeMillis(); for (int i = 0; i <= count; i++) { try { s.pop(); } catch (EmptyStackException e) { } } s2 = System.currentTimeMillis(); System.out.println((s2 - s1) + " milliseconds"); } }
上述代码示例将产生以下结果 -
Testing for empty stack
46 milliseconds
Catching EmptyStackException
1561 milliseconds
|