首页 > 解决方案 > 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();
    }
}

标签: c#exception

解决方案


我相信您正在寻求创建除 .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";

        }
    }

推荐阅读