创建自定义的异常或使用内置的异常?异常、自定义

2023-09-02 11:58:43 作者:寒烟锦瑟弦

目前我在写作,利用爱抛出异常其他类中的DNS,插座和SSL客户端类的过程。其他人将实现这个类,所以我在想,最好的做法是什么抛出异常。

Currently I'm in the process of writing a client class that utilizes DNS, Sockets, and SSL among other classes that love to throw exceptions. Other people will be implementing this class, so I was wondering what the best practice is for throwing exceptions.

我应该创建自己的自定义异常,让他们知道,这是我的课抛出异常或者我应该让我打电话(DNS,插座等)抛出自己的异常类和方法?目前,code是在数百行,并与许多不同的方法调用生长。什么是在这种情况下抛出异常的最佳做法?

Should I create my own custom exception so they know that it is my class throwing the exception or should I allow the classes and methods I call (DNS, Sockets, etc.) to throw their own exceptions? Currently, the code is in the hundreds of lines and growing with many different method calls. What is the best practice for throwing exceptions in this situation?

推荐答案

如果该BCL包含的类已经传达你想要的意思( ArgumentNullException ,例如),使用那些。

If the BCL contains classes that already convey the meaning you want (ArgumentNullException, for instance), use those.

储备用自己的异常类的东西是特定于API。

Reserve using your own exception classes for things that are specific to your API.

如果你觉得你可以添加信息,通过各种手段提高自己的异常,但不吞例外 - 它们传播了自己作为内部异常

If you feel that you can add information, by all means raise your own exception but do not swallow exceptions - propagate them up as inner exceptions of your own.