gpt4 book ai didi

c# - 类库与其他项目的异常处理技巧

转载 作者:行者123 更新时间:2023-11-30 19:57:40 24 4
gpt4 key购买 nike

我对在方法层次结构中处理异常有点困惑。

比方说,我在类库项目中有一个类 Logger。请查看以下代码-

namespace MyLibrary
{
public class Logger
{
//exposed to other project
public static void CreateLog(String message)
{
try
{
WriteInFile(message); //calling the method below
}
catch (Exception Ex)
{
throw Ex;
}
}

//private method
private static void WriteInFile(String message)
{
try
{
//Writing in a file
}
catch (Exception Ex)
{
throw Ex;
}
}
}
}

假设我在 ASP.NET MVC 项目中使用该库。代码-

namespace MvcProject.Controllers
{
public class HomeController : Controller
{
public ActionResult DoSomething()
{
try
{
Logger.CreateLog("some text.");
}
catch (Exception Ex)
{
//Exception is handled here.
}

return View();
}
}
}

层次结构:DoSomething() -> CreateLog() -> WriteInFile()

所有这三个方法都有 try.. catch.. block 。我的问题是-

  • 我真的需要在 CreateLog()WriteInFile() 方法中使用 try..catch 吗?

  • 如果我在所有方法,对性能有影响吗?

这是一个虚构的例子来解释问题。

It would be more useful for me if you post an answer with a revised code block that you suggest.

谢谢。

最佳答案

Do I actually need try.. catch in every method?

没有。事实上,它通过切断堆栈跟踪来损害您的诊断 - 您将无法看到原始的完整堆栈跟踪。你可以通过使用来解决这个问题:

throw;

代替

throw Ex;

...但基本上 try/catch block 只是在这里添加了多余的东西。摆脱它们。

If I use that in all the methods, does it have any performance impact?

仅当抛出异常时 - 但每次重新计算堆栈跟踪可能会使其变慢。不过,我不会担心性能 - 首先要担心代码的可读性(以及对堆栈跟踪的影响)。

关于c# - 类库与其他项目的异常处理技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com