Home   Cover Cover Cover Cover
 

User-defined exception classes

/csbook/solutions/12/A04.cs
using System;

class Stack {
  private int[] data;
  private int sp;
  private int size;
  
  public Stack(int size) {
    data = new int[size];
    sp = 0; 
    this.size = size;
  }
  
  public void Push(int x) {
    if (sp + 1 == size) throw new OverflowException(x);
    data[sp] = x;
    sp++;
  }
  
  public int Pop() {
    if (sp == 0) throw new UnderflowException();
    sp--;
    return data[sp];
  }
}

class OverflowException: ApplicationException {
  public int val;
  public OverflowException(int val) { this.val = val; }
}

class UnderflowException: ApplicationException {}

class Test {
  
  static void Main(string[] arg) {
    Stack stack = new Stack(10);
    try {
      foreach (string s in arg)
        stack.Push(Convert.ToInt32(s));
      for (int i = 0; i < 10; i++)
        Console.WriteLine(stack.Pop());
    } catch (OverflowException e) {
      Console.WriteLine("-- stack overflow: {0}", e.val);
    } catch (UnderflowException) {
      Console.WriteLine("-- stack underflow");
    } catch {
      Console.WriteLine("-- conversion error");
    }
  }
  
}