Should exceptions be publicly available

I know this is a good thing that always makes exceptions serializable . But should I always publish them? Even if they should only be caught domestically? I wonder if there could be any security problems or serialization problems (for example, sorting by application domain) if the exceptions are not public.

+4
source share
4 answers

Yes they should .

If you know that the exception will always depend on your own code, then it's OK to make it internal .

+4
source

In fact, there is nothing wrong with having internal exceptions if they are not part of your interface. This means, however, that

  • either the exception should absolutely not cross the boundaries of your module,
  • or you provide a general base exception that users of your module can catch.

Actually, it is a good idea to declare an exception type for the public base for your module, so your users can always rely on it in their catch . Separate exceptions derived from the base class may be publicly available if you prefer, but may not be so.

Note that you absolutely must not rely on the public / private mechanism to provide any security, because it can easily be overridden by a simple reflection.

+4
source

This is the same as defining a domain. Everything should be in the proper amount.

If you throw an exception in a specific class and use only that exception inside the class, then it should only have a scope inside the class, and therefore it should be private. However, this is not common.

In the second case, you have an exception that will be passed to another object that calls your class, you must make it public. This is the most common use of an exception, so most exceptions should be publicly available.

0
source

Think about it ... How far does the chain go? If an exception is selected from a public function, it must be public.

However, if the exception is always caught in your library and has never been thrown or was not reused or thrown like anything else, it may be internal.

Ideally, I would have a scenario like this:

 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 { } } 

Thus, users of my API have the opportunity to catch any exception that I throw. Domestic never make it this far.

0
source

All Articles