public Optional<Student> findStudent(String name, String` surname,String nickname)
{
try {
return repository.findOne(predicates.hasSpecifications(name, String surname,nickname));
} catch (IncorrectResultSizeDataAccessException e) {
return Optional.empty();
}
}
the method findOne() throws IncorrectResultSizeDataAccessException if more than one entry is found for the predicate inside of it. Is this the best way to handle the exception thrown? or should the caller handle the exception using something like: optional.orElseThrow()... but this method only handles NoSuchElementException (if no value is present) and not IncorrectResultSizeDataAccessException (If more than 1 RESULT)...
Any ideas guys?
Yeah, this would be the best way to do it.
I'm assuming hasSpecifications is a custom method which returns the id you wish to use to index the database
The thing is "findOne" and "hasSpecifications" are two methods independent of each other.
When we talk about abstraction, in methods then the only things that matter are their input parameters, the return values and the errors that may or may not be thrown.
This means "findOne" only cares about what "hasSpecifications" evaluates to. If there is an error or exception thrown while "hasSpecifications" is still executing then this error abruptly terminates the program (unless caught) and findOne wont even be evaluated (Because it was waiting for the id). A NoSuchElementException cannot be thrown because findOne hadn't started executing yet.
So since it's a custom method, the error handling has to be done by you, as you just did.
To make it more obvious extract predicates.hasSpecifications into a variable on a preceeding line and then place the variable in "findOne"
Related
I have service, a simple class that need to take input and run some business logic. Before executing this service, the user must set all the data. In general, it look like this:
public class TestService extends InnerServiceBase {
/**
* Mandatory input
*/
private Object inputObj;
#Override
protected ErrorCode executeImpl() {
//Some business logic on inputObj
return null;
}
public void setInputObj(Object inputObj) {
this.inputObj = inputObj;
}
}
What is the best runtime exception to throw in case the inputObj is null ?
IllegalStateException seems like the best fit. The object is not in the correct state to have executeImpl() called on it. Whatever exception you use, make sure the error message is helpful.
Whether you should be using an unchecked exception at all is a whole other question...
Depends on the scenario.
If this is part of an API that another developer is using, throwing NullPointerException is reasonable since you don't want that input to be null. Adding a descriptive exception message would be helpful.
If you're not interested in throwing an NPE, or this is part of code that's not going into an API, then you could throw an IllegalArgumentException, as null could be considered an illegal argument.
If setInputObj is called with a null argument, and that's not valid, then throw NullPointerException. There's some debate over the "correct" exception here (IllegalArgumentException or NullPointerException for a null parameter?), but Guava, Apache Commons Lang and even the JDK itself (Objects.requireNonNull) have settled on NPE.
If executeImpl is called before inputObj has been set, throw IllegalStateException.
I have some function works with database.
I have set a try/catch for error handling here, and display a message, It works fine.
Now the class calling this delete function need to know if there is a error or not. In my case : refresh the GUI if success, nothing to do if fail (as there already show up a message message dialog).
I come up a idea to return boolean in this function.
public static Boolean delete(int id){
String id2 = Integer.toString(id);
try {
String sql =
"DELETE FROM toDoItem " +
"WHERE id = ?;";
String[] values = {id2};
SQLiteConnection.start();
SQLiteConnection.updateWithPara(sql, values);
} catch (SQLException e) {
Main.getGui().alert("Fail when doing delete in DataBase.");
System.out.println("Exception : "+ e.getMessage());
return false;
}
return true;
}
Don't know if this is good or bad, please tell.
EDIT :
Here is more detail for How do I use :
Let's say the code above is inside Class A,
in Class B :
public boolean deleteItem(int id){
int i = index.get(id);
if(theList[i].delete()){ //<---- here is the function from Class A
theList[i] = null;
index.remove(id);
retutn true;
}
retutn false;
}
I need to pass the boolean in more than one class, I don't know if that can better through...
in Class C :
public void toDoList_deleteItem(){
MyButton btn = (MyButton)source;
int id = btn.getRefId();
List toDoList = Main.getToDoList();
if(toDoList.deleteItem(id)){ //<-------function in Class B
Main.getGui().refresh();
}
}
Edit 2 :
I have notice the question is somehow more likely asking "What should I handle a Exception at database Layer that affect to GUI Layer ?"... Something like that. Please correct me if the question title should be edit.
It looks like you are returning a boolean status to indicate that an exceptional condition had occurred. Generally, this is not a good practice, for two reasons:
It encourages an error-prone way of handling exceptions - it is very easy to miss a status check, leading to ignored errors
It limits your API's ability to report errors - a single pass/fail bit is not always sufficient, it may be desirable to pass more information about the error.
A better approach would be to define an application-specific exception, and use it in your API. This forces the users of your API to pay attention to exceptional situations that may happen, while letting you pass as much (or as little) additional information as you find necessary. At the same time, your code does not get polluted with if (!delete(id)) { /* handle error */ } code on each API call, shrinking your code base, and improving its readability.
Can you tell me more about "define an application-specific exception", or show some code example please?
Here is how I would do it:
public class DataAccessException extends Exception {
... // Define getters/setters for passing more info about the problem
}
...
public static void delete(int id) throws DataAccessException {
try {
... // Do something that may lead to SQLException
} catch (SQLException se) {
// Do additional logging etc., then
throw new DataAccessException("Error deleting "+id, se);
}
}
Note: It is common to give custom exceptions four constructors mirroring the constructors of the Exception class to allow exception chaining. The constructors are described here.
As long as you do not want the caller to know what happens, just that it fails (and that failing is part of its intended behavior) you should be fine.
That being said, I am noticing this: Main.getGui().alert("Fail when doing delete in DataBase.");.
It would seem that you are accessing the GUI layer from some other place. This might cause issues should you decide to multi-thread your application. Also, it is usually considered good practice to have your layers not intersect.
Don't return a Boolean, return a boolean. Since this is not an exception / error condition, it is fine.
Exceptions should be used when you don't expect a failure.
In your case, if it's fine for you that a SQLException is thrown and does not affect your program, it's ok to return a boolean.
If the SQLExcetion causing the delete to fail can cause problems in another part of your application it's better to throw an exception.
Edit:
Based on your edits, it seems that you are doing some maintenance and cleaning when an error happens. In such a case I would recommend to use Exceptions better than using booleans to control the execution.
This question is primarly opinion based. Personally I would prefer not to catch the exception at that point.
Depending on what the caller of delete() should do, you might need other resulutions. So you should better add a throw statement and let the calling method decide if the error is critical - or if it can proceed.
Just true and false is not necessary enough to let the caller decide correctly. He won't know if deletion fails due to database errors, due to foreignkey constraints, or something else.
letting the exception bubble up the call stack will provide the caller with the exact error going on, increasing the chance to handle the error in a proper way, or just displaying a custom error message helping the user to take proper actions.
Say we have a method changeUserName(Long id,String newName) which invokes the repository's findUser(Long id) to find the right user entity and then change its name. Is it appropriate to thow an IllegalArgmentException when findUser returns null ? Or should I instead throw a custom UserNotExistException (extends AppException extends RuntimeException) ?
UPDATE:
RuntimeException:
#nachokk #JunedAhsan Actually I deliberately make all the exceptions unchecked , because I think this way makes client code clean , easy for debuging and more safe. As to those "unhandled" ones, I'll catch them all on the top of layers thus avoiding showing them on the UI.
This is due to the fact that many clients catch checked exceptions and then just ignore it, and in some cases they don't know how to handle it. This is a hidden trouble.
Clarification:
Sorry for my bad English. What I meant is if the changeUserName should throw an IllegalArgumentException, not the findUser method. And another question: how to differentiate illegal argument from business rule violation?
You should use UserNotExistException. The name is very declarative of what is happening. In my opinion you should to avoid returning null but if you do you have to document it.
UPDATE
I was thinking and as #JunedAhsan suggest, UserNotExistException could be better a CheckedException (extends from Exception and not RuntimeException).
From this link: Unchecked Exceptions : Controversy
If a client can reasonably be expected to recover from an exception,
make it a checked exception. If a client cannot do anything to recover
from the exception, make it an unchecked exception.
/**
* #return User found or throw UserNotExistException if is not found
*/
public User findUser(Long id) throws UserNotExistException{
//some code
User user = giveMeUserForSomePlace();
if(user == null){
throw new UserNotExistException();
}
return user;
}
It depends on how you handle exceptions.
IllegalArgumentException is ok if you only display error report by using e.getMessage() and you don't care repetitive string appending code.
Here is some advantage I find by using custom exceptions:
1. Reduce reptetive code:
Let's say changeUserName is surely not the only case you'll load User, so this code snippet below will happen everytime you invoke repository.findUser(Long id)
if (user == null) {
throw new IllegalArgumentException("No such user found with given id["+ userId +"]");
}
On the other hand, an ad-hoc exception is much more handy:
if (user == null) {
throw new UserNotExistException(userId);
}
public class UserNotExistException extends RuntimeException {
public UserNotExistException(Long id) {
super("No such user found with given id["+ id +"]");
}
}
2. You need more support from your exceptions:
Maybe you need to return status code or something like that. An custom exception hierachy may do some help:
see this answer for detail.
I would too suggest to use UserNotExistException but with a difference that instead of it being unchecked exception (by virtue of extending RuntimeException), make it checked exception (extending Exception if AppException is not doing this already).
This will make sure that caller of changeUserName handles UserNotExistException exception and make the code a bit robust.
I am trying to execute below written code and the code should throw an exception but it isn't doint it
try {
Field.class.getMethod("getInt", Object.class).setAccessible(false);
StringSearch.class.getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.getClass().getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.searchChars(cc,pattern3);
ss4.searchString(str,pattern);
}
catch(NoSuchMethodException ex){
ex.printStackTrace();
}
it should actually throw IllegalAccessException.
ss4 is an object of class BNDMWildcardsCI (one of the algo for String search)
cc, pattern3 are character arrays
str, pattern are Strings
why it isn't throwing an exception, it is not throwing the NoSuchMethodFound exception means that it is able to find the method also i tried to print the isAccessible and it says false
but when i run the tests it doesn't throw any exception
To the best of my knowledge, if a method is declared public (or otherwise accessible), setAccessible(false) can't make it private. It's only useful if you have a private method and you previously called setAccessible(true).
The method setAccessible(boolean) work on object reflect not on normal object. In your code you set it on a method object not on the ss4 object.
To show my point:
Class<?> clazz = ss4.getClass();
Method searchCharsMethod = clazz.getMethod("searchChars",cc.getClass(),pattern3.getClass());
searchCharsMethod.setAccessible(true);
You have set the accessible flag to false on object assigned to searchCharsMethod not ss4.
As bonus see what happen when you call
searchCharsMethod.invoke(ss4,cc,pattern3);
For more please read the documentation
I came across a design that overrides [Scriptable.put][1] in a subclass of ScriptableObject to do some conversion. If the conversion fails the code is throwing an exception. Which means that property assignments like following code can cause a runtime exception to be thrown
aScriptable.dateOfArrival = aVar;
By default rhino wouldn't let the script catch a runtime exception thrown during [Scriptable.put][1]. So catch block in following code will never run:
try{
aScriptable.dateOfArrival = aVar;
}catch(e){
//will not run even if above assignment generates an exception. Script will be terminated instead
}
Overriding ContextFactory.hasFeature() with following code makes the above catch block work:
protected boolean hasFeature(Context cx, int featureIndex) {
if(featureIndex == Context.FEATURE_ENHANCED_JAVA_ACCESS){
return true;
}
return super.hasFeature(cx, featureIndex);
}
My question is that whether the design decision to make property assignment throw exception is correct or property assignments are never supposed to throw exceptions?
[1]: http://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/Scriptable.html#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
IMO it doesn't make sense to throw an exception by design from the put method that JS code can't catch. I think throwing an exception on setting a property is fine, although not that common. Note that JS code can easily reconfigure a property (in ECMAScript 5) with a custom setter that throws.
On the other hand, I think it would be quite surprising if a property getter throws an exception.