Solution:
public class StringException extends Exception{
private String str;
public StringException(String str){
this.str=str;
}
public String toString(){
return "Enter your name correctly";
// exception message here you can type whatever you want
}
}
// Next Class
import java.util.*;
public class UserDefinedException{
public static void main(String[] arg) throws Exception{
String str = getstring();
Boolean flag= false;
for(int i=0; i<str.length();i++){
if (((str.charAt(i) < 91) && (str.charAt(i) > 64))||(str.charAt(i) < 123) && (str.charAt(i) > 96))
flag=true;
else
throw new StringException(str);
}
if(flag == true)
System.out.println("Your name is " + " "+ str);
}
static String getstring(){
Scanner input=new Scanner(System.in);
System.out.println("enter your name");
String m =input.next();
return m;
}
}
// Output
Test1:
enter your name
Faizal
Your name is Faizal
Test2:
enter your name
Faizal12345
Exception in thread "main" Enter your name correctly
at UserDefinedException.main(UserDefinedException.java:11)
Post a Comment