using GLib; using Gee; public errordomain StackError { CANT_POP_FROM_EMPTY_STACK, CANT_PEEK_AT_EMPTY_STACK, } public class Stack { private ArrayList stack_elements; public Stack () { stack_elements = new ArrayList (); } public int Count { get { return stack_elements.size; } } public void push (T element) { stack_elements.add (element); } public T pop () throws StackError { if (stack_elements.size == 0) throw new StackError.CANT_POP_FROM_EMPTY_STACK ("Cannot pop() from empty stack."); int last_element_index = stack_elements.size - 1; T last_element = stack_elements.get (last_element_index); stack_elements.remove_at (last_element_index); return last_element; } public T peek () throws StackError { if (stack_elements.size == 0) throw new StackError.CANT_PEEK_AT_EMPTY_STACK ("Cannot peek() at empty stack."); return stack_elements.get (stack_elements.size - 1); } public bool trypeek (out T element) { if (stack_elements.size == 0) return false; element = stack_elements.get (stack_elements.size - 1); return true; } } public static void process_stack (Stack stack) { // Alternative #1 --- "check, try and assert on failure" if (stack.Count == 0) { //... handle empty stack here ... } else { string element1; if (!stack.trypeek (out element1)) assert (false); stdout.printf ("element1 == %s\n", element1); } // Alternative #2 --- "checked exception" if (stack.Count == 0) { //... handle empty stack here ... } else { string element2; try { stdout.printf ("element2 == %s\n", stack.peek ()); } catch (StackError.CANT_PEEK_AT_EMPTY_STACK e) { assert (false); } } // Alternative #3 --- "dont check, just try and then handle failure" string element4; if (stack.trypeek(out element4)) { stdout.printf ("element4 == %s\n", element4); } else { //... handle empty stack here ... } // Alternative #4 --- "unchecked exception" (works in C# but not in Java/Vala) if (stack.Count == 0) { //... handle empty stack here ... } else { stdout.printf ("element3 == %s\n", stack.peek ()); } } public static void main (string[] args) { Stack stack = new Stack (); stack.push ("hello"); process_stack (stack); }