IText Constructor not Throwing Exception or Following Flow - java

I have a static method used to get the title from a PDF using the metadata via itext, which is used as a small part of a major Task.
I noticed an inexplicable path that I narrowed down to this section of code. Specifically, in the line where I instantiate a PdfReader, the process doesn't throw an exception or continue through to the print statement. In fact, it clears out all of my for loops up to the top level of my program and acts as if nothing has happened and my task completed.
try {
System.out.println("Entered method");
PdfReader myReader = new PdfReader(file.getAbsolutePath());
System.out.println("Reader instantiated"); //if no issues, prints to console
Map<String, String> info = myReader.getInfo();
System.out.println(info.get("Title"));
return info.get("Title");
} catch (IOException e) {
System.out.println("PdfReader throws exception"); //if issues, prints to console
e.printStackTrace();
}
Unless I'm mistaken, when this set of code is executed in my method, either "Reader Instantiated" or "PdfReader throws exception" is printed out to the console.
Neither happens. Instead, the process skips every if/for/while loop it is currently in and ends the task.
I'm wondering if someone can explain to me what is happening and how I should go about fixing it?

In the odd event this is searched for, yes, catching Throwable stops the thread from bailing out. I had never seen something like this before. The cause behind the problem was that a PDF was password-protected, so getInfo() failed.

Related

How to catch Neo4j TransientException: LockClient

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
}
}
}

why not debug rather why exception handling

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.

(Java) Thread Inexplicably Stalling at an Exception Catch

I'm stuck in the middle of a real headscratcher here. My program gets to a point where it's supposed to throw an Exception and have it caught by it's parent process, except somewhere in there, the Thread seems to simply stop functioning and I can't explain why.
My program is very complex, but here is the essence of my problem {
public class ClassOne {
public CustomClass computeCustomClass() throws IOException {
//CustomClass is an elsewhere defined valid class in my code.
try {
//The core code of this "computeCustomClass" operation has the
//potential of throwing a "CustomException", an Exception class
//of my own creation.
} catch (CustomException e){
//I have inserted a logging utility here and it is logging that
//this "catch" process is definitely being executed.
//I will now wrap the CustomException in an IOException, as the
//core code of "createCustomClass()" has the potential to generate
//it's own IOExceptions, and the handling of a CustomException should
//be done just the same by a parent process as if an IOException had
//occurred.
throw new IOException(e);
}
}
}
public class ClassTwo {
private ClassOne myObject;
public void processData(){
try{
//I've inserted a logging code here to track when this line is
//executed.
CustomClass data = myObject.computeCustomClass();
//Another bit of logging code goes here and records when the
//"computeCustomClass()" request goes off without a hitch.
// Code goes here that processes the "data" variable;
} catch (IOException e){
//There is logging code here, but it NEVER records this "catch"
//section being executed! Even when the "CustomException" catcher
//in ClassOne.computeCustomClass() is logged as having executed!
//It's as if the thread running this code abruptly stops without
//throwing any exceptions/errors or any indication as to what's
//occurred!
}
}
}
To make matters all the more confusing, I have another thread that runs concurrently to the one that executes the above code. One of this second thread's jobs is to post regular logs about the other thread. Even after whatever occurs that prevents the "catch IOException" code from executing, the thread that SHOULD be executing it reports a "true" value for "isAlive()", and a "false" value for "isInterrupted()".
I don't know what's happening. Any ideas why it might be stalling here, or can somebody suggest a way of diagnosing what the failure actually is?
I see from grepCode that constructing an exception with a cause actually calls the toString() method on the cause.
If your custom exception has a toString() method that could throw an exception or cause some significant time delay then this could be a source of your problem.
You could also - temporarily - use:
//} catch (IOException e){
} catch (Throwable e){
just in case you catch block is being bypassed.

exception handling, creating log and continue the program in JAVA

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

Java - ignore exception and continue

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?

Categories

Resources