NegativeLengthException.java Illustrates defining and throwing your own exceptions. #Programming Code Examples #Java/J2EE/J2ME #Basic Java


import java.io.*;

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NegativeLengthException extends Exception {

  /** Test NegativeLengthException */

  public static void main(String[] args) {
    try {
      int lineLength = readLength();
      for(int i=0; i<linelength ; i++) {
        System.out.print("*");
      }
      System.out.println();
    } catch (NegativeLengthException nle) {
      System.out.println("NegativeLengthException: " +
                         nle.getMessage());
    }
  }

  public NegativeLengthException() {
    super("Negative dimensions not permitted.");
  }

  public NegativeLengthException(String message) {
    super(message);
  }

  // readLength catches IOExceptions locally but lets the
  // calling method handle NegativeLengthExceptions.
  private static int readLength() throws NegativeLengthException {
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    System.out.print("Enter length: ");
    System.out.flush();
    int len = 0;
    try {
      String line = in.readLine();
      len = Integer.parseInt(line);
      if (len < 0) {
        throw new NegativeLengthException();
      }
    } catch (IOException ioe) {
      System.out.println("Problem reading from keyboard");
    }
    return(len);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10223
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada