Description

throw new exception

Demo

class Calculator {
  // instance variables
  private int n = 0;
  private int p = 0;

  static int power(int n, int p) throws Exception {
    int result;/*from  w ww.j  av a  2  s  . c  om*/
    if (n >= 0 && p >= 0) {
      result = (int) Math.pow(n, p);
      return result;
    } else {
      throw new Exception("n and p should be non-negative");
    }
  }
}

public class Main {

  public static void main(String[] argh) {
      int n = 2;
      int p = 3;
      Calculator myCalculator = new Calculator();
      try {
        int ans = myCalculator.power(n, p);
        System.out.println(ans);

      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
  }
}

Related Topic