简体   繁体   English

哪种方法更好地使用异常?

[英]What way is better to use exceptions?

I have two ways for create exception. 我有两种创建异常的方法。

The first way: I use base Exception class for create exception. 第一种方式:我使用基本Exception类创建异常。

public class Class1
{
    public void Method1()
    {
        try
        {
            Method1ThrowException();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    public void Method1ThrowException()
    {
        throw new Exception();
    }
}

The second way: In this way I create User-Defined Exception class and then use this class for create exception. 第二种方式:通过这种方式,我创建了用户定义的异常类,然后使用该类创建异常。

public class Class2
{
    public void Method2()
    {
        try
        {
            Method2ThrowException();
        }
        catch (MethodException e)
        {
            Console.WriteLine(e);
        }
    }

    public void Method2ThrowException()
    {
        throw new MethodException();
    }
}

public class MethodException : Exception
{
    public MethodException()
    {

    }

    public MethodException(string message) : base(message)
    {

    }

    public MethodException(string message, Exception inner) : base(message, inner)
    {

    }
}

What the difference between this ways use of exception? 这种使用异常的方式有什么区别?

I read that use the second way is better and I don't understand why? 我读到使用第二种方法更好,但我不明白为什么? In both of ways I just create exceptions and get them. 在这两种方式中,我只是创建异常并获取它们。

The second way is better because you create your own exception type which can be suitable for specific situation. 第二种方法更好,因为您可以创建适合特定情况的自己的异常类型。 For example: you could create ConnectionBrokenException type when writing application which communicates over some network and throw it when connection is broken. 例如:您可以在编写通过某些网络进行通信的应用程序时创建ConnectionBrokenException类型,并在连接断开时抛出该类型。

This gives you two main advantages: 这给您两个主要优点:

First 第一
You can handle exceptions in different ways depending on the exception type using try..catch block. 您可以使用try..catch块根据异常类型以不同方式处理异常。 You may decide to show message to user, rollback some operations or do other stuff. 您可以决定向用户显示消息,回滚某些操作或执行其他操作。

try
{
    ... code throwing ConnectionBrokenException
}
catch(ConnectionBrokenException ex)
{
    _logger.LogError("Something bad has happened with connection", ex.Message);
}
catch(Exception)
{
    // handles other types of exceptions
}

Second 第二
When analyzing logs from such application it is easier to diagnose some problems when each bad situation has its own exception. 在分析来自此类应用程序的日志时,如果每种不良情况都有其自己的异常,则更容易诊断出一些问题。 You can for example use some filtering to find only exception you're interested in. 例如,您可以使用一些过滤来仅查找您感兴趣的异常。

Because catch (Exception e) catches everything . 因为catch (Exception e)捕获了所有内容 There is no way to discriminate what kind of exception was raised. 无法区分引发了哪种异常。 Thus, fine-grained error classes are good. 因此,细粒度的错误类是好的。

(Also, why define Method1ThrowException , instead of just throw ing the exception where it needs to be thrown? This just adds a useless layer to the stacktrace.) (另外,为什么定义Method1ThrowException ,而不是只throw荷兰国际集团需要的地方抛出的异常?这只是增加了一个无用的层堆栈跟踪。)

There is no 'better' way, as it depends on your specific needs. 没有“更好”的方法,这取决于您的特定需求。

If there is an existing exception type you can use, just use that one ( ArgumentException etc). 如果可以使用现有的异常类型,则只需使用该异常类型( ArgumentException等)。 See here for a list. 请参阅此处以获取列表。

If you need special exception type, create your own, containing your own custom properties. 如果需要特殊的异常类型,请创建自己的包含异常的自定义属性。 Example: 例:

 public BusinessException : Exception
 {
     public BusinessException(string reason)
     {
           Reason  = reason;
     }
     public string Reason {get; set;}
 }

If you are throwing these in a WCF service, be sure to add a global exception handler to map these exceptions to WCF faults. 如果要将它们扔到WCF服务中,请确保添加全局异常处理程序以将这些异常映射到WCF故障。 In case of web API, map them to HTML status. 如果是Web API,请将其映射为HTML状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM