什么时候最好使用try和catch?当我使用try和catch(有些甚至-1我......)回答问题时,我得到了愤怒的回答.我用谷歌搜索它并找到了这篇文章以及这个stackoverflow 问题.
我举一些例子:
我有一个带有时区ID的下拉列表,当用户选择他的时区时我正在更新数据库.在其他应用程序中,我从数据库中提取该值并重新计算用户当前时间和日期.可以选择DB中的数据拼写错误(DB或bug中的硬编码更改).在用户的日期时间的转换方法我正在使用try和catch,有些人告诉我这是错误的!我可以使用for循环来检查数据库中的值,但是每次转换日期时间都要花费更多...
我必须声明XML文件是否使用此代码格式良好:
protected bool IsValidXML(string xmlFile)
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlFile);
}
catch(XmlException ex)
{
///write to logger
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我看不到任何其他方法来检查xml文件.
有时我在我的应用程序中有一部分我正在写一个文件.写入文件可能会导致exeprtion,原因很多,其他一些进程在写入或其他时使用此文件.所以我通常使用这段代码:
using (StreamWriter w = new StreamWriter(fs))
{
try
{
w.Write("** (Line) " + someValue + " **" + Environment.NewLine);
w.Flush();
}
catch(IOExeption ex){}
finally
{
w.Close();
}
}
Run Code Online (Sandbox Code Playgroud)总之,我看到了一些使用try和catch以及不使用方法的方法.我看到的文章中的一句话说如果发生异常,你需要知道它.,但是在大多数时候处理泛型应用程序时,我知道会发生异常,但大多数时候我都不知道它为什么会发生,所以我以前无法捕捉到它(就像我写的那些例子),所以何时最好使用try和catch
在ASP.NET中的同一级别,页面有一个Error事件,您可以像这样捕获:
this.Error += new EventHandler(Page_Error); //this = instance of System.Web.UI.Page
Run Code Online (Sandbox Code Playgroud)
事件是否与try …
我在这篇文章中读过,为了避免"程序停止工作"对话框,我需要从AppDomain中捕获未处理的异常.
public Form1()
{
///Code
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
///more code
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var excep = e.ExceptionObject;
//Writing the exception to log file with the stack flow
Logger.Logger.LogException("UNHANDLED EXCEPTION:"+Environment.NewLine +excep.ToString(), this);
//Terminate the logger (manual event waiting for file write to finish)
Logger.Logger.Terminate();
Environment.Exit(1);
}
Run Code Online (Sandbox Code Playgroud)
但是当我被吸入异常时.我可以看到它写在日志上,但应用程序显示"程序停止工作"对话框.它可以由Logger.Terminate线路引起吗?(再次 - terminate命令等待,直到所有日志都写入日志文件)
我已经将ASP.NET web API self hostNuGet包管理器添加到我的项目(一个Windows服务项目)中,Nuget添加了这些库
当我尝试添加Route属性时,我无法在System.Web.Http中找到它.当我在MSDN中寻找这个类时,我看到它在这个包下
我需要安装另一个包还是添加另一个包?
嗯...我在 StackOverflow 中阅读了很多问题,但仍然没有得到答案,我有这个 Web API 控制器:
public class ERSController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
resposne.Content = new StringContent("test OK");
return resposne;
}
[HttpPost]
public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
//Some actions with database
resposne.Content = new StringContent("Added");
return resposne;
}
}
Run Code Online (Sandbox Code Playgroud)
我给它写了一个小测试:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54916/");
client.DefaultRequestHeaders.Accept.Clear();
var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");
var response …Run Code Online (Sandbox Code Playgroud)