c# - C# 抛出异常或 ToString 以引用字符串参数
问题描述
如果我为消费者编写 dll,在 catch 范围内有什么更好的方法,抛出异常或将其写入引用或输出字符串参数?
据我所知,异常确保故障不会被忽视,因为调用代码没有检查返回码。https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions
以下 2 个选项中哪个是最好的?
选项A
static void ThrowException(string value)
{
try
{
//Some code....
}
catch (Exception)
{
//Log Exception
throw;
}
}
选项 B
static void RefException(string value, ref string errorMessage)
{
try
{
//Some code...
}
catch (Exception ex)
{
//Log Exception
errorMessage = ex.ToString();
}
}
解决方案
我相信您正在寻求创建除 .net 异常之外的自定义异常
使用以下代码更新您的代码,并根据您的需要创建自定义异常。
public void ThrowException()
{
if (string.IsNullOrEmpty(value))
{
throw new NullException();
}
if (value.Length > 10)
{
throw new LengthException();
}
}
public class NullException : Exception
{
NullException() : base(NullException.GetMessage())
{
}
public static string GetMessage()
{
return "value is null or empty";
}
}
public class LengthException : Exception
{
LengthException() : base(LengthException.GetMessage())
{
}
public static string GetMessage()
{
return "value length greater then 10 exception";
}
}
推荐阅读
- listview - 我可以使用最初未声明的 itemCount 定义 ListView Builder
- python - 输入是一个int,变量是一个字符串,如果字符串大于if语句中的int,我想要一个动作。python3.8
- mysql-8.0 - 如何在 MySQL 8.x 版中找到完全匹配
- dynamics-crm - UciError:将值添加到产品表单中支持的小数时,精度值 3 无效
- c# - 更改角度模板时 nswag 生成的文件返回结果关键字未考虑
- java - Spring Boot Web 服务依赖问题
- c# - 优化多个if条件进行flag检查
- c# - 与通道松弛集成时,自适应卡没有以正确的外观和感觉出现
- amazon-web-services - 在 Amazon S3 上打包文件
- r - 为什么 ggsurvplot_facet 忽略 pval.size?