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);
        }   
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user2545071
  • 1,408
  • 2
  • 24
  • 46

3 Answers3

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.

Henrik
  • 23,186
  • 6
  • 42
  • 92
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

Surfbutler
  • 1,529
  • 2
  • 17
  • 38
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?

Hexie
  • 3,955
  • 6
  • 32
  • 55