-
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.
-
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.
Code:
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.
Code:
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.");
}
Similar Threads
-
Replies: 0
Last Post: 03-10-2003, 10:36 AM
-
By Lenok in forum Database
Replies: 2
Last Post: 09-26-2002, 12:31 PM
-
By Larry Leach in forum .NET
Replies: 0
Last Post: 03-15-2002, 04:05 AM
-
By Michael Welch in forum .NET
Replies: 4
Last Post: 03-05-2002, 11:07 PM
-
Replies: 3
Last Post: 01-24-2002, 03:27 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|