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
}
}
}
Related
I am trying to execute a sql statement in Listener's contextInitialized method, but when I run gretty local server, it throws RuntimeException error. I can't figure out, why. It doesn't run into any errors when i comment out ps.executeQuery();.
#Override
public void contextInitialized(ServletContextEvent sce){
ServletContext sc = sce.getServletContext();
DataSource pool = new ConnectionPoolFactory().createConnectionPool();
String sql = "create table test (id int);";
try (Connection conn = pool.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException();
}
}
"Doctor, it hurts when I press here!"
Well, stop doing that then.
This:
} catch (SQLException e) {
throw new RuntimeException();
}
is in a word insane. You're taking a useful error which includes 5 convenient aspects that will help you figure out what went wrong:
The actual type of the exception (Could be a subclass of SQLException; 'DatabaseNotAvailableException', for example)
The message associated with it
The stack trace which points precisely at the line of code that caused it
The cause - exceptions can have causes, which are themselves exceptions (well, throwables). The cause is often more useful than the exception itself.
The chain of swallowed exceptions. This is rarely useful.
You've decided to pitch them all into the garbage, to replace it with a single RuntimeException that gives no useful information of any sort or kind whatsoever.
Do not do that.
Proper exception handling involves being a lot less scared of the throws clause on methods. Got a method that does DB stuff, and the design of this method is clearly indicated to do so (if the method is named 'query' or otherwise contains any word that obviously indicates SQL, the answer is clearly: Yes, it does), then that method should be declared to throws SQLException, for example.
Secondarily, in the rare cases where throwing it onwards does not work out, if you catch an exception, you do not want to just log it and continue, and you do not want to throw some other exception without setting up a cause first. This is the standard 'I do not know what to do and I do not want to spend any further time on thinking about it' exception handler:
} catch (ThingIDoNotWantToThinkAbout e) {
throw new RuntimeException("Unhandled", e);
}
That , e is crucial, it sets up the actual exception as cause, so that you actually see it in your stack traces and logs. It is very common to see a standard exception handling of e.printStackTrace(). Do not do this - 90% of java examples are bad. This causes all sorts of problems, because the 'logs' go to standarderr (which is a lot less flexible than letting them go to the exception handler of the context within which you are operating. For example, if writing a web handler, e.printStackTrace() just dumps stack. Throwing an exception upwards will dump stack and allow the framework to add information about the request that triggered the problem, and serve up a suitable HTTO status 500 error page. Also, by just running printStackTrace, the code will continue execution, which is obviously not what you want: Something went wrong - continuing blindly onward will either guarantee that your software silently does the wrong thing, or causes further exceptions, thus resulting in a single error causing hundreds of stack traces flooding your syserr.
Once you've fixed this problem here and everywhere else in your code, the actual problem will most likely be clear as day. Something about the SQL server being down or a syntax error in your SQL.
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 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;
I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the program must not stop here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file.
You're looking for the try-catch block. See, for example, this tutorial.
OutputStream os = ....;
PrintStream ps = new PrintStream(os);
while(notDone) {
try {
doStuff();
}
catch(Throwable t) {
t.printStackTrace(ps);
}
ps.print(results);
}
the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
To do all of these, it is better to surround your code with try catch block
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?