OneCompiler

Define an exception called "NoMatchException" that is thrown when a string is not equal to "India". Write a program that uses this exception.

791

class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message);
}
}

public class Main {
// Method to check if the string matches "India"
static void checkString(String str) throws NoMatchException {
if (!str.equals("India")) {
throw new NoMatchException("String does not match 'India'");
}
}

public static void main(String[] args) {
    try {
        // Pass a string to checkString method
        checkString("USA");
    } catch (NoMatchException e) {
        // Handle the exception
        System.out.println("Caught NoMatchException: " + e.getMessage());
    }
}

}