Need Help Writing Exception code.
Hey y'all, this is probably a simple a question but i'm not used to writing exceptions...
The program is easy, basically I had to make a program that takes the user input on a length of a square, then it prints out the square in *''s, and then states the area and perimeter, i have all that, but then you have to write an exception class if the user inputs a number such as "0" which is invalid.
So here is my driver....
Code Java:
import java.util.*;
public class SquareDriver {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String input ="";
System.out.println("Welcome to the easy square program");
while(true)
{
System.out.println("Enter the length of the side of a square or enter QUIT to quit");
try
{
input = keyboard.nextLine();
if(input.equalsIgnoreCase("quit"))
break;
int length = Integer.parseInt(input);
Square s = new Square();
s.setLength(length);
s.draw();
System.out.println("The area is "+s.getArea());
System.out.println("The perimeter is "+s.getPerimeter());
}
catch(DimensionException e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
and then here is my Dimension Exception, I don't even want an entire answer, if someone could kindof help point me into the direction to get started it would be much appreciated!
Code Java:
public class DimensionException extends Exception
{
}
Re: Need Help Writing Exception code.
I think you're doing step 2 (catching the Exception), when you want to be doing step 1 (throwing the Exception). That way whoever calls your code can catch the Exception you throw. You don't do the catching, they do. You do the throwing.
So the question is, when do you want to throw your Exception?
Re: Need Help Writing Exception code.
The driver was all given by my professor, and told not to alter the driver code.
If the dimension is set improperly throw the DimensionException
Re: Need Help Writing Exception code.
What about the Square class? Is the setLength method supposed to throw a DimensionException?
Re: Need Help Writing Exception code.
The question remains: when do you want to throw your Exception?