nightshadz
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(); ?
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();
}
}
}
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I meant to remove the FileNotFoundException clause. Thanks for your input guys!
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:
Open in new window