hello everyone. when working with objects, how would one specify that the input of negative numbers is not allowed in the constructor part of the code?

Since you can't return an error code from a constructor, you could throw an Exception if the parameter(s) are not acceptable:

class X {
   public X(int value) throws Exception {
      if (x<0) throw new Exception("Parameters must not be negative");
...

thanks! that helps with that problem...but now i am getting another error. on the object lines of code;

c1 = new CircleObj(inputx,inputy,inputradius);

it says "unhandled exception type Exception"

sorry if this is basic stuff, i am very new to this.

you are getting that error because in your constructor part you specified that an Exception is thrown therefor any calls to that exception must handle that thrown Exception.

To solve that problem surround your code with a try - catch clause

try{
     c1 = new CircleObj(inputx,inputy,inputradius);
}catch(Exception ex){
//put some error messages here or any error handlers
}

alright, but now it is saying that my variable c1 has not been initialized..

after i edit the code with the try catch

System.out.println("Results for Circle #1");
	System.out.println("X: "+c1.getX());
	System.out.println("Y: "+c1.getY());
	System.out.println("Radius: "+c1.getRadius());

Edited 7 Years Ago by shroomiin: n/a

declare your c1 variable outside the try catch and initialize it with a null value ..something like

CircleObj c1 = null;
      try{

      c1 = new CircleObj(inputx,inputy,inputradius);

      }catch(Exception ex){

      //put some error messages here or any error handlers

      }

Note: Anything you declare inside the try-catch is a local variable in that clause so if you declare c1 inside the try catch you can only use it inside that clause.

This article has been dead for over six months. Start a new discussion instead.