user3587624
user3587624

Reputation: 1471

Find out specific Exception

Apologies for the lack of information...

Is there a way to find out what is the specific Exception that is causing a call to throw the Exception?

Currently, I am catching all the Exceptions by doing catch(Exception e) but I know this is not good practices at all.

Is there a way to know from the Exception what is the specific one that caused the issue so I can be more granular?

Upvotes: 1

Views: 1365

Answers (4)

Robyn MacCallum
Robyn MacCallum

Reputation: 206

You can get more information for the particular exception using different methods on it. Here I'm using the System.Diagnostics.Debug class to print in Visual Studio's output console. In your catch block:

using System.Diagnostics;

try  
{
    // do stuff
}
catch (Exception e)
{
    Debug.WriteLine(e.GetType());  // Displays the type of exception
    Debug.WriteLine(e.Message());  // Displays the exception message
}

You can see more here: Exception methods & Exception properties

Upvotes: 3

Christoph Sonntag
Christoph Sonntag

Reputation: 4629

If you want to make it more specific for logging errors, try something like:

e.GetType()

Or, if you need some more information like the StackTrace or message:

e.ToString()

If you only want to catch a specific type of exception, you need to do something like:

try {
   // someCode
} catch (SpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}
catch (AnotherSpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}

Upvotes: 0

Igor
Igor

Reputation: 62213

Option 1 - Documentation

Read the documentation of the method you are calling, if it is a Framework Class type (like SqlConnection.Open) the thrown exceptions are well documented.

Option 2 - Discover them at Run Time

If its a 3rd party library and documentation is limited then check the Exception at runtime using exception.GetType() and then add known exceptions you want to handle as catch blocks.

Personally I prefer to not add catch blocks at all where I am not sure if an Exception will materialize or not. If/When it does the debugger will break (if it is set to break) or you have a global catch all that logs and rethrows. Then you get the type and update your code accordingly. Where you add such a global Exception logger depends on the type of application you are developing. If you go the route of a global logger do take note that you 1) rethrow the Exception so the app breaks at runtime and not swallow it and 2) rethrow using throw; syntax (not throw ex;).

Upvotes: 2

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

You can catch different types of exceptions. With this solution you are able to handle the different types easily.

try
{
    //Try something
}
catch (StackOverflowException soe)
{
    //Handle StackOverFlowException
}
catch (FormatException fe)
{
    //Handle FormatException
}
//... Other exceptions

Upvotes: 0

Related Questions