Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Exceptions. Please help.

Hi, i'm new to java (which is why im posting it here :)). I was just wondering if someone can write me a sample code for exception. Nothing fancy, just a few lines. Lets say ive got my main function and thats doing something. In my main , im asking a user to input their first name (of course, this is string). What i want to do is, if the user has entered in nothing or if they've entered in a number (as a person cannot have numbers in their name), then i want an exception just saying that "You have entered a number as your first name, please try again". Basically, i want my exceptions to be handled in another class completely and i would like them to be triggered when that happens. Could someone help me please? Thanks.
[737 byte] By [coolio2005] at [2007-11-11 8:17:37]
# 1 Re: Exceptions. Please help.
When you throw an exception, the operation is just canceled usually. If you just want to ask the user to try again due to invalid input, you don't really need to worry about exceptions.

public class TestException
{
private String name = "";

public TestException(String name)
{
this.name = name;
}

public void setName(String s) throws Exception
{
if (s == null || s.equals(""))
throw new Exception("String is either null or empty");
}

public static void main(String[] args)
{
TestException test = new TestException("johnny");

try{
test.setName("");
}
catch(Exception e){
System.out.println(e);
}
}
}

The while loop will continue until the user has entered valid input.

String input = "";

while (input == null || input.equals(""))
{
//prompt user for input...

//validate input
if (input == null || input.equals(""))
System.out.println("Sorry, invalid input. Please try again.");
}
Phaelax at 2007-11-11 22:35:52 >