Link to home
Start Free TrialLog in
Avatar of nightshadz
nightshadzFlag for United States of America

asked on

Is this exception handling a type of polymorphism?

If this code throws a FileNotFoundException, would catching it as type Exception be considered Polymorphism? I understand Polymorphism as being able to invoke derived class methods from a base class variable, so this could look something like
Exception e = new FileNotFoundException(); ?

    
    class ExceptionHandlingExample
    {
        static void Main(string[] args)
        {
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(@"C:\Sample Files\Data.txt");
                Console.WriteLine(sr.ReadToEnd());                
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("Please check if the file {0} exists.", e.FileName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally //Will run even if there is an additional exception in a catch block
            {
                if (sr != null) { sr.Close(); }
                Console.WriteLine("Finally Block");
                Console.ReadLine();
            }
        }
    }

Open in new window

Avatar of Ironhoofs
Ironhoofs
Flag of Netherlands image

I am not sure what you are asking, but i'll try

Specific exceptions (like FileNotFoundException) are derived from Exception. Its a easy way to get additional information about an error if you want, but you don't have to.

You can catch the default Exception and convert back to the specific exception, but the additional information has been lost. Example:
try {
	throw new System.IO.FileNotFoundException("test.xml");
}
catch (Exception e) {
	System.IO.FileNotFoundException ex = e as System.IO.FileNotFoundException;
	MessageBox.Show("FileNotFound " + ex.FileName);
}

Open in new window

Avatar of nightshadz

ASKER

Hi, thanks for your response. I'm just asking if catching a FileNotFoundException as type Exception would be considered a form of Polymorphism as shown above?
SOLUTION
Avatar of Ironhoofs
Ironhoofs
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I meant to remove the FileNotFoundException clause. Thanks for your input guys!