Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in java exception type for permission exceptions

Tags:

java

exception

With the view that where it makes sense, we should always use built in exceptions rather than define our own, ie:

  • IllegalArgumentException - Thrown when a method is passed an invalid parameter, ie null is not allowed
  • IllegalStateException - Thrown when method is called when it is not allowed to be (ie setup() must be called first.

What is the best exception type to throw (if any) when you are throwing an exception due to a user attempting to read or write a resource they do not have permission to operate on. Would you recommend using SecurityException or AccessControlException, or does that sound non-sensical.

like image 223
Jay Avatar asked Dec 11 '22 17:12

Jay


2 Answers

In my opinion, neither of them. Each exception class serves a purpose, and in this case SecurityException is the class of exceptions thrown by the SecurityManager (which is part of the JRE), and AccessControlException is a sub type of SecurityException.

I think it is not correct (even though the name is pretty) to throw a SecurityException when the real cause was that an application-defined permission was not granted (as opposed to permissions enforced by the SecurityManager).

You should consider that exceptions are meant to be catch by code that is expected to be able to know how to deal with them. If some function does not know how to "fix" an exception, the exception should be allowed to bubble up the stack. Any code dealing with SecurityException will surely not know how to deal with the exceptions raised by your application.

like image 138
Javier Avatar answered Dec 14 '22 06:12

Javier


From http://docs.oracle.com/javase/7/docs/api/java/security/AccessControlException.html:

This exception is thrown by the AccessController to indicate that a requested access (to a critical system resource such as the file system or the network) is denied.

The reason to deny access can vary. For example, the requested permission might be of an incorrect type, contain an invalid value, or request access that is not allowed according to the security policy. Such information should be given whenever possible at the time the exception is thrown.

Sounds pretty close the scenario you're describing. I'd go with AccessControlException.

Note there's even a constructor that takes a Permission object.

like image 37
pamphlet Avatar answered Dec 14 '22 06:12

pamphlet