0

I have foreign class, which throw Exception "Unknown exception". I want to catch it in my code and write message like "Error! Do this steps:...".

So, my code:

try
{
    var p = new MyObject(prms); // this code failed and throw exception-"Unknown exception" 
    
    return p;
}
catch (Exception ex)
{
    // Output ex 
    Console.WriteLine("Error! "+ex.Message);
}

How to wrap foreign exception and show my text? Thanks!

P.S. foreign code looks like that:

try
        {
            lock (_lockObject)
            {
                return MyObject();
            }
        }
        catch (Exception exp)
        {
            throw ThrowWrapper(exp);
        }   
5
  • 1
    So what problem are you having with your code? It looks ok to me.
    – Surfbutler
    Sep 30, 2013 at 10:03
  • 2
    Define foreign exception? As it stands this code will catch any exception within the try.
    – Lloyd
    Sep 30, 2013 at 10:07
  • Ah maybe you're talking about wrapping the original exception inside your own, so that the original one is the inner exception?
    – Surfbutler
    Sep 30, 2013 at 10:11
  • This might help: stackoverflow.com/questions/12603295/…
    – Surfbutler
    Sep 30, 2013 at 10:16
  • Surfbutler , yes i want to wrap the original exception inside my own) Sep 30, 2013 at 11:50

3 Answers 3

1

Classes don't throw exceptions, functions do. If the constructor of MyObject throws an exception, the shown code will catch it. If another member function of MyObject throws, you need a try-catch where this member function is called.

0

A good example of how to wrap a 'foreign' exception inside your own exception can be found here: http://msdn.microsoft.com/en-us/library/vstudio/system.exception.innerexception(v=vs.90).aspx

0

Why not do something simple like;

Using your existing code; (see the code change in the catch)

try
{
    var p = new MyObject(prms); // this code failed and throw exception-"Unknown exception" 

    return p;
}
catch (Exception ex)
{
    If (ex.Message.Contains("Unknown exception"))
       {
         //Add code here to handle the Unknown exception
       }
    else
       {
         Console.WriteLine("Error! "+ex.Message);
       }
}

Please note that this is a "quick" way of handling this, the correct way would be to create your own exception and handle that as some of the other answers suggest.

Hope that helps.

Will that not achieve what you are wanting?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.