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. Edit/Delete Message
public String getName() throws Exception {
String s = javax.swing.JOptionPanel.showInputDialog(null, "Type in something");
if (s == null || s.length < 1)
thrownew Exception("this is an error message");
elsereturn s;
}
You can put the getName method in any class you want. You may want to make it static, so you don't need to create an instance of the class containing the method.
Note: I didn't compile the code, there may be some errors in the code, but nothing you can't resolve. This is just to give you an idea.
Thanks for your reply. Ok so if i'm getting user input from my main function, how does that interact with your code. If the user has inputted (for e.g. 12344555666) as their name, obviously that is wrong. So how does my code interact with the other exception class which i'm creating. Also, do i need to add anything in my main?