Program to throw a user-defined exception "String Mismatch Exception", if two strings are not equal (ignore the case)
This is a simple program in which we have two checked two strings for equality. If they are equal then print "String matched !!!" otherwise throw user-defined exception. The euqlasIgnoreCase( ) method of java.lang.String class is used to compare two strings by ignoring case considerations.
PROGRAM
PROGRAM
import java.util.Scanner;
class StringMismatchException extends Exception {
public StringMismatchException(String str) {
System.out.println(str);
}
}
public class StringExcDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the string :: ");
String input = scan.nextLine();
try {
if(input.equalsIgnoreCase("Hello"))
System.out.println("String matched !!!");
else
throw new StringMismatchException("String not matched ???");
}
catch (StringMismatchException s) {
System.out.println(s);
}
}
}
OUTPUT 1
C:\>javac StringExcDemo.java C:\>java StringExcDemo Enter the string :: Hello Strings matched !!!OUTPUT 2
C:\>javac StringExcDemo.java C:\>java StringExcDemo Enter the string :: HELLO String matched !!!OUTPUT 3
C:\>javac StringExcDemo.java C:\>java StringExcDemo Enter the string :: Hi Strings mismatch ??? exception.StringMismatchException