对于C#中的错误处理,存在更好的代码(例如,对于全局错误处理)而不是try ... catch还有更多的错误信息(错误号和错误代码行)? [英] Exists a better code (e.g. For global error handling) on error handling in C# than try...catch with more error information as well (error number and error code line)?

查看:98
本文介绍了对于C#中的错误处理,存在更好的代码(例如,对于全局错误处理)而不是try ... catch还有更多的错误信息(错误号和错误代码行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#应用程序中节省大量时间和空间,不要用try ... catch结构包围每一行代码以避免错误。它模糊了我的代码并且每次打字都要输入它。我试图做一些全局错误处理。



示例(V​​B 6):On Error Resume Next。 (=使用单行程序对整个应用程序执行错误处理。无论如何都执行代码!)



C#是否有类似内容?

然后我需要更多关于异常的错误信息。只是要知道XY类型的例外对我来说还不够。

我需要错误编号(例如错误编号56)和错误行(例如第578行中的错误)(发生错误的代码行号)和函数名称(例如void form_load(。 ..))错误被触发的地方。

C#似乎没有提供有关异常的信息。所以我很难弄清楚错误是什么。有什么想法吗?



我尝试过:



< pre lang =c#> 尝试
{
// 这里要处理的代码行
}
catch (Exception Ex1){MessageBox.Show( Ex1.Message); Process.Start( shutdown - f);}





这给我提供的信息不足错误。我希望看到错误编号(例如错误编号65)和错误代码行(例如第578行中的错误)以获得关于究竟发生了什么的更多跟踪信息。



然后我需要在整个应用程序上进行全局错误处理,而不是每行都有这个问题。



任何解决方案或更好的全局错误处理命令?

尝试...捕获绝对不是我要去的东西。



关闭整个系统之前的任何注销对话框错误也很好。

解决方案

如果需要,Exception类可以提供大量细节,包括行号和完整的堆栈跟踪。检查此代码段的输出以进行演示:

  private   void  input_btn_Click( object  sender,EventArgs e)
{
try
{
int x = 0 ;
int y = 1 ;

int z = y / x;

}
catch (例外情况)
{
Console.WriteLine( --------------------);
Console.WriteLine(ex.Message);
Console.WriteLine( ----------------- ---);
Console.WriteLine(ex.ToString());
Console.WriteLine( ----------------- ---);
Console.WriteLine(ex.StackTrace);
}
}



为了更好的全局错误处理技术,本文是必读的异常处理.NET中的最佳实践 [ ^ ]



原样这个 Vexing例外|编码中的精彩冒险 [ ^ ]


我假设您想捕获并对代码中的所有未处理异常执行某些操作。我会留给你把正确的使用陈述放在你文件的顶部。



做这样的事情:



在main.c函数开头附近的main.cs中:



 Application.ThreadException + = < span class =code-keyword> new  ThreadExceptionHandler(UnhandledExceptionEventHandler); 

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

AppDomain.CurrentDomain.UnhandledException + = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);





然后,写下这样的处理程序:



  public   void  CurrentDomain_UnhandledException( object  sender,UnhandledExceptionEventArgs e)
{
ExceptionHandler((Exception)e.ExceptionObject);
}

public void UnhandledExceptionEventHandler( object sender,ThreadExceptionEventArgs e)
{
ExceptionHandler(e.Exception);
}

public void ExceptionHandler(例外e)
{
string result = FormatException(e, string .Format( 信息:{0} \ n\\\
,Assembly.GetEntryAssembly()。GetName()));


// 在此处执行您想要的结果。
}

public string FormatException(例外e,< span class =code-keyword> params string [] information)
{
Exception ex = e;
StringBuilder sb = new StringBuilder();

if (information!= null
{
foreach 字符串 s 信息)
sb.Append(s);
}
while (ex!= null
{
sb.AppendLine(ex.GetType()。ToString());
sb.AppendLine(ex.Message);
sb.AppendFormat( \ n \ nStack Trace:\ n {0},ex.StackTrace);
ex = ex.InnerException;
if (ex!= null
sb.AppendFormat( \ n \ nInner异常:\ n \ n);
}
return sb.ToString();
}


I would like to save a lot of time and space in my C# application not to surround each single line of code with a "try...catch" construct to avoid errors. It obscures my code and to type it each time is tiring off. I seek to do some global error handling.

Example (VB 6): On Error Resume Next. (=error handling done for whole application with a one-liner. Code get executed no matter what!)

Is there something alike for C#?
And then I would need some more error information on the exceptions. Just to know that there was an exception of type XY is not enough for me.
I need the error number (e.g. error no. 56) and the error line (error in line 578 e.g.) (code line number where the error happened) and function name (e.g. "void form_load(...)") where the error was triggered.
C# seems not to supply such informations on exceptions. So I have a hard time to figure out, what the error is about. Any ideas on this?

What I have tried:

try
{
//here the code line to handle
}
catch(Exception Ex1){MessageBox.Show(Ex1.Message); Process.Start("shutdown" "-f");}



This provides me not enough information about the error. I would like to see the error number (e.g. error no. 65) and the error code line (e.g. error in line 578) to have more tracking informations about what exactly happened.

Then I would need a global error handling on whole application, not this per line thing all the time.

Any solutions or better global error handling commands on this?
try...catch is definitely not the thing for me to go.

Any logoff dialog before shutting down the whole system on error would be also nice.

解决方案

The Exception class can provide a great deal of detail if you need it, including the line number and a complete stack trace. Examine the output from this code snippet for a demonstration:

private void input_btn_Click(object sender, EventArgs e)
{
    try
    {
        int x = 0;
        int y = 1;

        int z = y / x;

    }
    catch (Exception ex)
    {
        Console.WriteLine("--------------------");
        Console.WriteLine(ex.Message);
        Console.WriteLine("--------------------");
        Console.WriteLine(ex.ToString());
        Console.WriteLine("--------------------");
        Console.WriteLine(ex.StackTrace);
    }
}


For better global error handling techniques then this article is a must-read Exception Handling Best Practices in .NET[^]

As is this Vexing exceptions | Fabulous Adventures In Coding[^]


I am assuming you want to catch and do something with all unhandled exceptions within your code. I will leave it to you to put the proper using statements at the top of your files.

Do something like this:

In your main within program.cs near the beginning of the function:

Application.ThreadException += new ThreadExceptionHandler(UnhandledExceptionEventHandler);

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);



Then, write your handlers like this:

public void CurrentDomain_UnhandledException(object sender,  UnhandledExceptionEventArgs e)
{
    ExceptionHandler((Exception)e.ExceptionObject);
}

public void UnhandledExceptionEventHandler(object sender, ThreadExceptionEventArgs e)
{
    ExceptionHandler(e.Exception);
}

public void ExceptionHandler(Exception e)
{
    string result = FormatException(e, string.Format("Information: {0}\n\n", Assembly.GetEntryAssembly().GetName()));


    // Do what you want with the result here.
}

public string FormatException(Exception e, params string[] information)
{
    Exception ex = e;
    StringBuilder sb = new StringBuilder();

    if (information != null)
    {
        foreach (string s in information)
            sb.Append(s);
    }
    while (ex != null)
    {
        sb.AppendLine(ex.GetType().ToString());
        sb.AppendLine(ex.Message);
        sb.AppendFormat("\n\nStack Trace:\n{0}", ex.StackTrace);
        ex = ex.InnerException;
        if (ex != null)
             sb.AppendFormat("\n\nInner Exception:\n\n");
    }
    return sb.ToString();
}


这篇关于对于C#中的错误处理,存在更好的代码(例如,对于全局错误处理)而不是try ... catch还有更多的错误信息(错误号和错误代码行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆