Home   Cover Cover Cover Cover
 

Hierarchy of exception classes

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

class PowerException: ApplicationException {}
class WrongBaseException: PowerException {}
class WrongExponentException: PowerException {}

class Test {
  
  static int Power(int x, int y) {
    if (x == 0) throw new WrongBaseException();
    if (y <= 0) throw new WrongExponentException();
    int res = 1;
    for (int i = 0; i < y; i++)
      checked {
        res = res * x;
      }
    return res;
  }
  
  static void Main(string[] arg) {
    try {
      Console.WriteLine(Power(2, 5));
      Console.WriteLine(Power(2, -5));
    } catch (WrongBaseException) {
      Console.WriteLine("-- base in Power must not be 0");
    } catch (WrongExponentException) {
      Console.WriteLine("-- exponent in Power must be > 0");
    } catch (OverflowException) {
      Console.WriteLine("-- arithmetic overflow");
    }

    try {
      Console.WriteLine(Power(0, 5));
    } catch (PowerException) {
      Console.WriteLine("-- wrong arguments in Power");
    } catch (OverflowException) {
      Console.WriteLine("-- arithmetic overflow");
    }
  }
  
}