Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should Exceptions always be public

Tags:

.net

exception

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 appdomains) if the exceptions are not public.

like image 666
bitbonk Avatar asked Feb 24 '23 09:02

bitbonk


2 Answers

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.

like image 74
SLaks Avatar answered Mar 07 '23 12:03

SLaks


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.

like image 33
Vlad Avatar answered Mar 07 '23 11:03

Vlad