开发者

Reference method and class of exception (c#, .net)

开发者 https://www.devze.com 2023-02-20 21:50 出处:网络
I have a class with a method and I want to throw an exception within the method. In this I would like to reference the method and class in which the exception wa开发者_开发问答s thrown to find the sou

I have a class with a method and I want to throw an exception within the method. In this I would like to reference the method and class in which the exception wa开发者_开发问答s thrown to find the source of the error more easily.

public class SomeClass
{
    public void SomeMethod()
    {
        (..)
        Throw new Exception("An error occurred. Method:" + ?? + ", Class:" + ?? +");
    }


You dont need to do that. Look at the StackTrace property of the exception in your try-catch block.


That information will already be in the stack trace. There's no need to include it in the message as well.

If you absolutely have to, there's MethodBase.GetCurrentMethod(). For the class, would you want the class of the execution-time object on which the method was called, or the method which is actually executing? (I would stick to the stack trace though...)


You actually already have all that information and just need to access it via the Exception's StackTrace property with something like:

        try
        {
            // to do something exceptional
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }

This sample just write to std out but you could do anything with the StackTrace information you want, including logging it to file or db.


You can actually use the StackTrace class for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消