Wednesday, October 30, 2013

Unable to catch automatically raised exception using derived exception class in catch block

Hi all, I am having problem in catching exception raised by .Net using custom exception in catch block.


What I did is I created a custom exception class derived from Exception, following is the code:



[Serializable]
public class DerivedException : SystemException, ISerializable
{
public DerivedException()
{
//
// TODO: Add constructor logic here
//
}
public DerivedException(string message)
:
base(message)
{
}
public DerivedException(string message, Exception inner)
:
base(message, inner)
{
}
protected DerivedException(SerializationInfo info, StreamingContext context)
:
base(info, context)
{
}
}

Then I then I tried to cause the exception using following code:



public void OpenThisFile()
{
try
{
File.Open(@"c:\test1234.txt", FileMode.Open);
}
catch(DerivedException ex)
{}
}

I the File.Open(... method I choose the file name which does not exist, so that this method cause exception. However, when the exception raised catch block does not catch it... can some body tell me why it is happening and how to get the exception caught using custom exception.


Any help in this regard would be heighly appreciated.


No comments:

Post a Comment