Catch Exception Block

G

Guest

Hi,
I have created a StringBuilder (Log) in my application that appends all the
errors and exceptions in my application. I have included Catch blocks at each
sensitive location in my functions.
I was wondering if there is a way that i can get the name of the function in
which the exception has occured like
try{}
catch(Exception e)
{
Log.Append(e.FunctionName + "--" + e.Message);
}

How can get the name of the function using e Args. I don't want to hard code
the FunctionName in each catch block.

Thanks!

With Regards
Sunny
 
N

Nicholas Paldino [.NET/C# MVP]

Sunny,

You can take a look at the StackTrace property of the Exception instance
that you catch. StackFrame instance at the bottom should be the stack frame
that threw the exception. You can then get the MethodInfo instance of the
method by calling the GetMethodInfo method on the StackFrame instance.

Hope this helps.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Use Exception.StackTrace

Take also a look at Exception.InnerException, it can contain also some info
you may be interested in.

Cheers,
 
J

Jay B. Harlow [MVP - Outlook]

Sunny,
In addition to the other comments, instead of (in addition to) using a
try/catch in each of your sensitive routines, consider having a global
exception handler, this way you only need to log the exception in a single
location.

Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.HttpApplication.Error event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomain.UnhandledException event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows.Forms.Application.ThreadException event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you
use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the
Application.ThreadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm
raises an exception, the Application.ThreadException handler will catch all
uncaught exceptions from any form/control event handlers.

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top