If a class method from package A throws its own exception defined in package A , and the class is used in package B , is it possible to make an exception class package private ? IDEA shows what you can. But then I can not catch him in B obtained?

  • Obviously not. Hence the conclusion - If you can’t catch a private exception, then you’ve done to make a private class no exception. Use the same Exception | RuntimeException. - Sergey
  • I have @Sergey inherited from RuntimeException , and if I don’t have to catch it? - insider Nov.
  • If you do not need to catch - do not catch. But if Runtime is necessary to catch, but it is not necessary, I do not even know. It after all in Runtime also will get. So the one who catches should distinguish him from others, and for this you need to make him public - Sergey

1 answer 1

It will not work to catch it in catch, because the code just won't compile

 catch (MyPrivateException e) // error 

It will be possible to catch it with a more general type.

 catch (Exception e) // MyPrivateException поймается 

But if someone wants in the handler to write different logic for different exceptions, problems arise, so it’s better not to do so.

 catch (Exception e) { if (e.getClass().getName().contains("MyPrivateException") { // единственный способ отличить такое исключение handlePrivateException(e); } else { throw e; } }