gpt4 book ai didi

c# - 主动抛出异常 vs 重新抛出 vs 包装和重新抛出

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:13 24 4
gpt4 key购买 nike

<分区>

如果我有一个类在做一些可能导致异常的事情,当我知道有问题时,最好在方法的主体执行之前抛出异常,即:

public class FileThingy
{
public void Do(string filepath)
{
if(!File.Exists(filepath))
{
throw new ArgumentException("File not here!");
}

// do file stuff
}
}

或者等到我期望的异常发生再抛出它:

public class FileThingy
{
public void Do(string filepath)
{
try
{
// do file stuff stuff
}
catch (FileNotFoundException ex)
{
throw;
}
}
}

或者等到我期望的异常发生并将其包装在一个更好地描述它的类型的新异常中,然后抛出它:

public class FileThingy
{
public void Do(string filepath)
{
try
{
// do file stuff
}
catch (FileNotFoundException ex)
{
throw new ArgumentException("File not here!", ex);
}
}
}

我已经看到所有这三种方法都在不同的地方使用,我想知道是否应该首选其中的任何一种,以及其中的任何一种是否特别有害。

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