简体   繁体   English

引用方法和异常类(C#、. net)

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

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 was 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. try-catch块中查看异常的StackTrace属性。

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() . 如果绝对必须 ,则有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: 实际上,您已经拥有了所有这些信息,只需要通过Exception的StackTrace属性使用以下信息进行访问:

        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. 该示例只是写出标准输出,但是您可以对所需的StackTrace信息执行任何操作,包括将其记录到文件或db中。

您实际上可以为此使用StackTrace类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM