Head-First-Design-Patterns icon indicating copy to clipboard operation
Head-First-Design-Patterns copied to clipboard

In java proxy example, bad usage of java.lang.IllegalAccessException

Open Nimamoh opened this issue 5 years ago • 0 comments

On the java proxy example, when creating the owner dynamic proxy: OwnerInvocationHandler

The logic is to prevent owner to call its setGeekRating, it is done throwing a java.lang.IllegalAccessException, unless I misunderstood, it is a really poor choice:

IllegalAccessException is used when trying to reflectively access something you have no right to in term of the language (i.e: trying to invoke a private method from outside). It is also a checked exception, which means it will be wrapped in a UndeclaredThrowableException (see InvocationHandler::invoke javadoc)

Since I follow the exemples quite loosely I were dubious about getting an UndeclaredThrowableException in my client code (which is not a problem on the book's examples since all exceptions are catched). I think a specific exception or even a generic RuntimeException would be more appropriate.

Nimamoh avatar Nov 22 '20 00:11 Nimamoh