should Exceptions always be public
I know that it is a good thing to always make exceptions serializable. But should I also always make them public? Even if they should only be caught internally? I wonder if there potentially be any security issues or serialization problems (e.g. marshalling across appd开发者_运维百科omains) if the exceptions are not public.
Yes, they should.
If you know that the exception will always be caught by your own code, then it is OK to make it internal
.
In fact, there is nothing bad in having internal exceptions if they are not a part of your interface. This means however that
- either the exception must absolutely never cross the borders of your module,
- or you provide a public base exception which the users of your module can catch.
In fact, it's a good idea to declare a public base exception type for your module, so your users can always rely on it in their catch
clauses. The individual exceptions derived from the base class may be public if you prefer, but may be not as well.
Please note that you absolutely must not rely on public/private mechanism in order to ensure any kind of security, because it can be easily overridden with plain reflection.
It is the same as scoping anything. Everything should be in the proper scope.
If you create an exception in a specific class and only use that exception inside the class, then it should only have a scope inside the class, and so it should be private. However, this is not common.
The second you have an exception that will be handed to another object calling your class, you should make it public. This is the most common use of an exception, so most exceptions should be public.
Consider this... How far up the chain is an exception going to reach? If an exception is going to be thrown from a public function then it should be public itself.
That said, if the exception is always caught within your library and either never thrown or re-badged and thrown as something else, it can be internal.
Ideally, I'd have this scenario:
namespace MyAPI
{
public class PublicException : System.Exception
{
}
// derive my public exceptions from this
public class CatchableException : PublicException
{
}
// stuff that should never reach the users of my API
internal class InvisibleException : System.Exception
{
}
}
This way, the users of my API have a facility to catch any exception that I throw. Internal ones never make it that far.
精彩评论