I am using Spring ROO.
In my web application I can create many users and save.
I can update the existing users as well.
For the update scenario we are using merge() method to update the existing data. In database, the column 'username' is unique. Following is the scenario.
The user create an user name 'Sean' with mobile number '6039274849'
The user create another user named 'Parker' with mobile number '8094563454'
When the user tries to update the second user 'Parker' with 'Sean', I am getting exception.
In the stacktrace I could see the following exception being the causes
caused by ConstraintviolationException
caused by SQLException
caused by TransactionSystemException
caused by PersistenceException
caused by TransactionRollbackException
I tried the do the following
public String merge()
{
try{
//code to merge
}
catch(????? e){
throw e;
}
}
I tried to add the above 5 exceptions in '????' . But I couldnot catch still.
Can anyone please tell which exception I need to add in '????' to catch the exception from the above list?
P.S: I am using Spring ROO. So I am changing code in .aj file. Please dont close this question as duplicate. I am expecting an answer from anyone for my issue before closing this question.
As a last resort, you can just catch the all-purpose exception
public String merge()
{
try{
//code to merge
}
catch(Exception e){
//handle e here.
}
}
Um, aren't you just rethrowing the exception in your catch? It should be the "most-recent" exception in the trace, so ConstraintValidationException.
Note that typically in Spring/Hibernate apps, the exception bubbling out of your code is what causes transactions to roll back. If you catch the exception, you will probably prevent that, which might lead to data inconsistencies.
When in doubt I try catching a Throwable and either add break point or log it out to see exactly what it is. Then change code accrodingly.
I had the same probelem lately. It seems that spring wrap exception in it's own exception class. I solved this problem with:
try {
...
}
catch(Exception e){
System.out.println(e.getClass().getName());
}
with that you will discover what exception has been realy thrown;
Related
I often get this kind of Exception
Exception in thread "main" org.neo4j.driver.v1.exceptions.TransientException: LockClient[21902] can't wait on resource RWLock[NODE(1423923), hash=286792765] since => LockClient[21902] <-[:HELD_BY]- RWLock[NODE(1419986), hash=869661492] <-[:WAITING_FOR]- LockClient[21905] <-[:HELD_BY]- RWLock[NODE(1423923), hash=286792765]
when I run Neo4j queries in my Java application. Now, this question has a good answer to the reason why this error occurs, and I can't do anything to improve my queries: I just need them as they are.
My question is: how can I catch this kind of exception? It occurs at this line of my code:
session.run(query, parameters);
but the Javadoc doesn't show any apparent Exception to be catched with a try-catch block.
Thanks in advance.
This is because TransientException is a runtime exception (E.G. a subclass of Java.lag.RuntimeException). It is not required to be in the method signature, and you are not required to put he method in a Try...Catch block. Try putting that line within a try...catch block and you should not get that exception anymore. How you handle it depends on the nature of your application. You could print a warning to log, and then error in the application, or even keep trying until the code worked.
Edit: after reading the answer you linked, I understand why you are getting these exceptions. I would put a Thread.sleep() in the catch block, then attempt the query again, in which case the error should go away. But then again, I am in no way a Neo4j expert so take my advice with a grain (truckload ) of salt
Edit 2: your code should look somewhat like this:
for(Query query : queries){
boolean flag = false;
while(!flag){
try{
query.execute();
flag = true;
} catch (TransientException e){
log("Retrying query "+query);
Thread.sleep(1*1000); //1 second
}
}
}
we specify the exception in try and catch.If we know what exception is gonna be generated why go for exception handling rather than just debug that part of the code?
According to Oracle definition of Exception
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
CONCLUSION:
If you put a try {} catch block you know will always trow an Exception, your code is wrong.
For example, this code compiles? YES, but is wrong
String s = "throwMe!";
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
}
CORRECT EXCEPTION USE
System.out.println("Enter a number");
String s = Scanner..... // user enters something
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
// TELL USER THERE IS A PROBLEM
}
// TELL USER IS A GENIUS
This will have 2 execution flows, the correct one (user is a genius) but in the moment the user enters a value disrupting the flow (Integer.parseInt(s);) the Exception is thrown...
No, exceptions refer to run-time conditions that we cannot foresee
For example, the divide-by-zero error happens due to user inputting wrong data.
So you catch with try-catch
try {
}
catch(ArithmeticException){
}
You don't have to do exception handling or debugging, you can do both and good exception handling helps you debug your code later on.
If nothing else a catch block should print the Stack Trace which gives you information regarding where things went wrong with your code and it's much better than failing silently and then manually debug your whole code to search for the problem.
There are many other advantages to using exceptions for error handling as well.
Try / catch blocks are for errors that you cannot foresee. Things like null pointers and divide by 0 errors don't need a try catch blocks. Those things are typically errors on the part of programmers and should be debugged by the programmers. But things like IOException or SQLException, where you are interfacing with some other system that could fail or give invalid input that the programmer cannot control, those things need a try / catch block.
I am using jpa with hibernate I want to insert 100 record in Database, suppose I get exception JDBC batch update in 50th record insertion i need to handling the Exception and I need to persist remaining record to DB.
Code:
private List<TempCustomers> tempCustomer =new ArrayList<TempCustomers>();
public String migrateCustomers() {
TempCustomers temp = null;
for(DoTempCustomers tempCustomers:doTempCustomers){
try {
temp=new TempCustomers();
BeanUtils.copyProperties(temp, tempCustomers);
tempCustomer.add(temp);
entityManager.persist(temp);
}catch (Exception e) {
tempCustomer.add(temp);
entityManager.persist(temp);
log.info("Exception ..."+e);
return "null";
}
}
return "null";
}
Nagendra.
What Mr. RAS is telling is correct.
For example you are persisting 100 entities and exception happened in the 50th Entity persist. You have exception handler it will work for you to handle the situation. It ll skip the current one and process the next one.
Things to take care as follows:
1- Your exception handling should be within the loop, hope you already have it.
2- For exception you can save the entity in different list for further analysis for error details. do it in the exception catch block.
3- I am not sure whether you are using the transaction manager or not, transaction need to take care.
--
In the 2nd case please remove the line...
entityManager.persist(temp);
as you already know this throws exception. keep it in the list for your further analysis. better put into any queue(ActiveMQ) upto you.
Best solution for this is again:
Validate all your data before persist...to minimize the exception. runtime things need your re-processing again and that should be manual.
Let's say I am designing an API for storing passwords. According to Effective Java it is a good idea to use throw clauses to show checked exceptions, however by having a throw clause that throws a SQLException, which is a checked exception, then I am revealing the underlying implementation details of my API and thus I will be unable to change the implementation details of my API at a later stage. One of the pros to throwing a checked exception is that the programmer who uses the API should be able to handle the exception in a manner of their choosing. Which of these two methods should I choose to do, add a throw clause which reveals the implementation or hide it or use a different approach?
Your motivation is correct for not "leaking" SQLException to the users of your class.
The fact that you're using SQL could be considered an implementation detail. You may even swap SQL persistence for say, an in-memory one at a later time, and this change shouldn't impact the users of your class.
If you are inclined to use checked exceptions, I would define your own exception type (say, PasswordStoreException -- just an example name). You can use it to wrap the original exception that was thrown, e.g.:
try {
// do whatever
} catch (SQLException ex) {
throw new PasswordStoreException(ex);
}
It is today considered bad design for an API to declare checked exceptions. If you have ever used such an API, you should already know why.
In any case your API should never throw (let alone declare) exceptions belonging to other APIs. If you do that, you hang a completely unrelated dependency on your client's back. The only "exception" to this rule are JDK's standard exceptions like NPE, ISE and the like.
Catch the SQLException, and wrap it into your own exception:
try {
// JDBC code
}
catch (SQLException e) {
throw new MyException("Error persisting the secret", e); // choose a better name, of course
}
Whether this exception should be a checked exception or a runtime exception depends on what the caller can do about it. If it's recoverable (which, I think, is not the case here), it should be a checked exception. If it's not recoverable (the caller can just display an error message), then it should be a runtime exception.
If it's a checked exception, you have no choice; the exception MUST be declared in the throws clause of the method.
As is, it is always a good idea to throw your own exception checked/unchecked. But before that, try to fix the underlying exception if possible. I always prefer the below way,
try {
// JDBC code
}
catch (SQLException e) {
// try to solve the exception at API level
bollean solvable = trySolveException(e);
if (!solvable) {
// Alert the admin, or log the error statement for further debugging.
mailClient.sendMailToDBAdmin("Some issue storing password", e);
// or
LOG.severe("some issue in storing password " + e.toString);
throw MyException("A request/logstatement is logged on your behalf regarding the exception", e);
}
LOG.info("The exception is solved");
}
finally {
// don't forget to free your resources - to avoid garbage and memory leaks, incase you have solved the issue in trySolveException(e).
}
So,
1) You don't expose the SRQException directly, but you throw your own version of the exception.
2) You tried to solve the exception once and if not you alerted somehow - through a mail or a log statement.
3) Finally, you ve released all the resources if you succeed in solving the exception.
The finally clause can be avoided if you use the new Java7's try with resource close option.
For whether to throw checked or unchecked exception, I will give you an example
1) Say an exceptions like NPE - they are programmatic errors and the developer should be more responsible to have not created a NullPointer. You don't expect your code to account for such careless errors and put a try(NPE), catch(NPE). So throw a unchecked exceptions.
2) On the other hand the exceptions like SQL exceptions are at the rare cases, account for some external dependency. So, better throw a user defined checked exceptions. And the user can determine if he can connect to the backup SQL server if any.
3) There are another clause of exceptions, where the program cannot continue furhter. Say a Memory Out of Bounds. They should be thrown as Errors.
Try this..
fillInStackTrace() method is called to re-initialize the stack trace data in the newly created throwable. Will be helpful in masking the info about the exception when tries to access the API.
For my Java application, I am creating an instance of a user information object and populating it with a service that I don't control the source for.
The code looks like this:
// username given as parameter
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (Exception e) {
// Whatever
}
If LDAPService.findUser() can't locate a user, it will throw a NullPointerException and grind the rest of my application to a stop. It's okay if the user information isn't populated, so I want to be able to continue without causing everything else to start throwing exceptions.
Is there a way to do this?
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz # your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
You are actually ignoring exception in your code. But I suggest you to reconsider.
Here is a quote from Coding Crimes: Ignoring Exceptions
For a start, the exception should be logged at the very least, not
just written out to the console. Also, in most cases, the exception
should be thrown back to the caller for them to deal with. If it
doesn't need to be thrown back to the caller, then the exception
should be handled. And some comments would be nice too.
The usual excuse for this type of code is "I didn't have time", but
there is a ripple effect when code is left in this state. Chances are
that most of this type of code will never get out in the final
production. Code reviews or static analysis tools should catch this
error pattern. But that's no excuse, all this does is add time to the
maintainance and debugging of the software.
Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?