2
Answers

inheritance

Photo of Shreya

Shreya

12y
1.3k
1

1)      What should i do next?

      Use Inheritance to create an exception base class and various exception –derived classes.Write a program to demonstrate that the catch specifying the base class catches derived –class exceptions.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

    class Excep : System.ApplicationException

    {

        public int num1, num2;

        public Excep(int a, int b)

        {

            num1 = a;

            num2 = b;

            if (num1 == 0 || num2 == 0)

                throw new Child1();

            else if (num1 < 0 || num2 < 0)

                throw new Child2();

        }

    }

 

    public class Child1 : Excep

    {

      

    }

 

    public class Child2 : Excep

    {

 

    }

 

    class MainClass

    {

        public static void Main()

        {

        try

        {

             Excep e1= new Excep(2,0);

           

        }

        catch (Excep)

        {

            Console.WriteLine("Caught Child 1");

        }

 

        try

        {

            Excep e2 = new Excep(2, -1);

        }

        catch (Excep)

        {

 

            Console.WriteLine("Caught Child 2");

        }

    }

}

class Child1 : System.Exception

{

}

class Child2 : System.Exception

{

}

Answers (2)

0
Photo of Vulpes
NA 98.3k 1.5m 12y
No, having just tried it, the code's not working and has a lot of problems.

I think you're trying to do too much with your exception classes, Shreya, which are really just providing information about some error that has occurred and rarely need to do any calculations.

As the question you've been given is vague, I'd just do something minimal like the following:

using System;

namespace ExceptionClasses
{
    public class Excep : System.ApplicationException
    {
        public Excep(string message) : base(message)
        {
        }
    }
 
    public class ChildExcep1 : Excep
    {
        public ChildExcep1(string message) : base(message)
        {
        } 
    }
 
    public class ChildExcep2 : Excep
    {
        public ChildExcep2(string message) : base(message)
        {
        }  
    }
 
    class MainClass
    {
        public static void Main()
        {
           try
           {
              throw new ChildExcep1("Child1 exception thrown");
           
           }
           catch (Excep e) // catch with base exception clause
           {
              Console.WriteLine(e.Message);
           }
 
           try
           {
              throw new ChildExcep2("Child2 exception thrown");
           }
           catch (Excep e) // catch with base exception clause
           {
              Console.WriteLine(e.Message); 
           }
        }
    }
}

The output should be:

Child1 exception thrown
Child2 exception thrown


0
Photo of Javeed M Shaikh
NA 7.8k 69.7k 12y
not sure what the question is , is this not working?