user2211907
user2211907

Reputation:

How do I find the exception type of an exception that gets thrown in C#?

I am using a library that doesn't seem to document the exceptions. This library is used to communicate with a product the company makes. I want to be able to differentiate between the exceptions that get thrown but I don't know the names of the exceptions (for example between a communication timeout or under-voltage condition).

All of their examples only use catch(Exception ex). How can can I find what I need to use to catch the individual errors? When I do ex.toString() I get something like this:

System.Exception: Timeout
    at CMLCOMLib.EcatObj.Initialize()
    at copley_cmo_test.MainWindow.btnConnect_Click(Object sender, RoutedEventArgs e)
in c:\Users\adam.siembida\Desktop\copley_cmo_test\copley_cmo_test\MainWindow.xaml.cs:line 41

Upvotes: 1

Views: 174

Answers (5)

Nahum
Nahum

Reputation: 7197

use a decompiler for example:

http://www.jetbrains.com/decompiler/

in .net there's no explicit exception declaration like in java so as i see it it's the only way.

Upvotes: -1

srsyogesh
srsyogesh

Reputation: 609

When the API in library which you are using is not documented properly , you should catch the base exception and log it not only by the message instead whole exception by converting the exception to string . Eg.

   try
   {
       //api call which throws exception.
   }
   catch(Exception ex)
   {
       //log ex.ToString();       
   }

Upvotes: 0

plinth
plinth

Reputation: 49179

By the way, if you're stopped when the exception has been caught (ie, in a catch block), if you enter $exception in the watch window, you will see the entire exception.

Upvotes: 0

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

Catch it with a catch-all construct such as catch(Exception ex), then examine the Type returned by ex.GetType(). If it's equal to typeof(Exception), it means that they aren't throwing anything more specific than Exception.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500065

This:

System.Exception: Timeout

shows that they're just throwing a bare System.Exception, e.g.

if (weHaveNoApiDesignSkills)
{
    throw new Exception("Timeout");
}

It's possible that there are some exceptions which are better designed, but the one you've shown isn't promising :(

Unfortunately unless you start using the message in the exception to differentiate between them (which is almost always a bad idea) you're stuck. It may be worth asking the authors of the library to see if they can improve matters for a future release.

Upvotes: 10

Related Questions