Define an Exception called “NoMatchException” that is thrown when a string is not equal to “India”. Write a Java Program that uses this exception.

import java.io.DataInputStream;
import java.io.IOException;

public class NoMatchException extends Exception {

 public static void main(String args[]){
     String s = new String();
     DataInputStream in = new DataInputStream(System.in);
     try{
         System.out.println("Enter the String:");
         s = in.readLine();
     }
     catch(IOException nme)
     {}
     try{
    
         if(s.equals("India"))
         {
             throw new NoMatchException();
         }
     }
     catch(NoMatchException nme){
         System.out.println("No Match Exception Caught: " +nme);
     }
 }   
}

4 comments:

  1. O/p:enter the string:US
    No Match exception caught.

    ReplyDelete
  2. why is the following code showing symbol not found at NoMatchException

    public class main1
    {
    public static void main(String s[])
    {
    try
    {
    //String s1=new String(s);

    if(s.equals("India"))
    {
    System.out.println("Entered string is India");
    }
    else
    {
    throw new NoMatchException();
    }


    }
    catch(NoMatchException e)
    {
    System.out.println("Entered String is not India");
    }

    finally
    {
    System.out.println("Completion of program");
    }

    }

    }

    ReplyDelete
    Replies
    1. the class name and the in the else statement has to be same

      Delete

Digital Marketing

Subscribe to RSS Feed Follow me on Twitter!