Java Programming Practical 13

Question 1
Write the simple program for throwing our own exceptions
OwnExceptionDemo.java
Java
				import java.util.Scanner;

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

public class OwnExceptionDemo 
{
    public static void main(String[] args) 
	{
        try {
			{
                throw new MyException("This exception is manually thrown");
            }
        } 
		catch (MyException e) 
		{
            System.out.println(e.getMessage());
        } 
    }
}
			
Output
Question 2
Define an exception called “NotMatchExceptons” that is thrown when a string is not equals to “India”. Write a program that uses this exceptions.
NotMatchDemo.java
Java
				import java.util.Scanner;

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

public class NotMatchDemo 
{
    public static void main(String[] args) 
	{
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter your string: ");
            String str = scanner.nextLine();

            if (!str.equals("India")) 
			{
                throw new NotMatchExcepton("String does not match");
            }

            System.out.println("String matched");

        } 
		catch (NotMatchExcepton e) 
		{
            System.out.println(e.getMessage());
        } 
    }
}
			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *