Same error line multiple times in error log - java

Could someone explain me what could be the reason for such an error log. When would this be printed. I am not able to understand and this is causing a performance issue in my app.
my error log is like below-
at xxx.createBooking(MailEJB3ServiceZipProxy.java:453)
at xxxx.onSelectBooking(Main.java:2524)
at xxxx.onSelectBooking(Main.java:2603)
at xxxx.onSelectBooking(Main.java:2603)
at xxxx.onSelectBooking(Main.java:2603)
at xxxx.onSelectBooking(Main.java:2603)
at xxxx.onSelectBooking(Main.java:2603)
at xxxx.onSelectBooking(Main.java:2603)
my catch block code looks like -
public void onSelectBooking(){
try{
////
} catch(ReservationBusinessException ex){
m_hModuleContainer.setBusy(false);
List mail = ex.getMailHeader();
m_hCargoRecordDTO = (CargoRecordDTO)mail.get(0);
ReservationObserver m_hReservationObserver= new ReservationObserver();
m_hReservationObserver.setCargoRecordDTO(m_hCargoRecordDTO);
m_hReservationParameterDTO.setReservationObserver(m_hReservationObserver);
ExceptionTab exceptionTab = new ExceptionTab(m_hReservationParameterDTO,m_hCargoRecordDTO,ex);
if ( exceptionTab.isErrorsOverridden() ){
// set all overridden flags
m_hCargoRecordDTO.setSoftErrorsAccepted(true);
m_hCargoRecordDTO.setErrorShown(true);
m_hMailHeaderDTO.addHtCar(m_hCargoRecordDTO);
onSelectBooking();**// line 2603**
}

Presuming the error printed before the first line is StackOverflowError, it's because you have infinite recursion, where the logic in the try block fails with ReservationBusinessException, causing the code to retry infinitely with a recursive call in line 2603, until the call stack is full.
There are 2 ways to fix this:
Change the code to use a loop, instead of recursion, to retry, e.g.
public void onSelectBooking() {
boolean retry;
do {
retry = false;
try {
...
} catch(ReservationBusinessException ex) {
...
retry = true; // instead of recursive call
}
} while (retry);
The problem with this solution is that the code may never complete, if the cause of the exception isn't resolved.
Limit the number of retries. This should be done using a loop like above but with a retry count instead of a boolean, but can still be done using recursion:
private static int MAX_RETRIES = 3;
public void onSelectBooking() {
onSelectBooking(0); // first attempt is not a "retry"
}
public void onSelectBooking(int retry) {
try {
...
} catch(ReservationBusinessException ex) {
if (retry > MAX_RETRIES) {
throw new RuntimeException("Max. number of retries (" + MAX_RETRIES + ") exceeded: " + ex, ex);
}
...
onSelectBooking(retry + 1);
}
}

Related

Print Message after successfully compilation

I have a simple JAVA code it will just print hello after compile and Run the Program. But I want to print one message after successful completion. Is this possible? If yes than how?
Although, the following code snippet is way too overkill for your task but, expanding on my comment - you may want to submit a custom task to a class
which implements Callable.
public class Main {
public static void main(String[] args) {
final ExecutorService executorService;
final Future<Integer> future;
final int statusCode;
executorService = Executors.newFixedThreadPool(1);
future = executorService.submit(new TextMessagePrinter());
try {
statusCode = future.get();
if (statusCode == 10) { // Printed successfully
System.out.println("JOB DONE. EXITING...");
Runtime.getRuntime().exit(0); // A zero status code indicates normal termination.
} else {
System.out.println("ERR...SOMETHING WEIRD HAPPENED!");
Runtime.getRuntime().exit(statusCode); // A non-zero status code indicates abnormal termination.
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdownNow();
}
}
}
class TextMessagePrinter implements Callable<Integer> {
public Integer call() {
Integer STATUS_CODE;
try {
System.out.println("Printing hello..."); // Try printing something
System.out.println("Dividing 6 by 0 gives us: " + 6 / 0); // And then you try to do something knowing which will result in an exception
STATUS_CODE = 10; // Indicates success.
} catch (ArithmeticException e) {
STATUS_CODE = 20; // Indicates failure...setting status code to 20.
}
return STATUS_CODE;
}
}
Running the above code on my IDE gives me the following output:
When the exception happens
(Note the status code set in the catch block getting printed when the process finishes):
No exception happens, everything happens fine:
(Comment the following line)
System.out.println("Dividing 6 by 0 gives us: " + 6 / 0);
If you mean completion of the application's Runtime, I think you are looking for the answer in this StackOverflow question: Java Runtime Shutdown Hook.
Or if you want to do what is in the question title and do something after building, then you may consider a build automation tool, like Maven.

java code to wait for parallel code to finish

I m having a server code to process an image.
Now there are n number of requests which tries to execute the code which results in OutOfMemory error or the server to hang and the server goes to not responding state.
To stop the code from executing at once all the requests I m limiting to execute the code one at a time using the below method where i have a variable
if the variable is 10 then wait for the variable to come at 0
if at 0 then set it to 10 then execute the code
run the code and finally set i to 0
The code here -
static newa.Counter cn;
public int getCounta() {
return cn.getCount();
}
public void setCounta(int i) {
cn = new newa.Counter();
cn.setCount(i);
}
at the function i m doing this -
public BufferedImage getScaledImage(byte[] imageBytes)
{
int i=0;
Boolean b = false;
BufferedImage scaledImage = null;
newa.NewClass1 sc = new newa.NewClass1();
try {
sc.getCounta();
} catch (NullPointerException ne) {
sc.setCounta(0);
}
i = sc.getCounta();
if(i==0)
{
sc.setCounta(10);
b = true;
}
else
{
while( b == false)
{
try
{
Thread.sleep(2000);
i = sc.getCounta();
if( i==0)
{
sc.setCounta(10);
b = true;
System.out.println("Out of Loop");
}
} catch (InterruptedException ex) {
System.out.println("getScaledImage Thread exception: " + ex);
}
}
}
..... execute further code
try { } catch { } finally { sc.setCounta(0); }
}
Is there any way I can have this simplified using the Runnable interface or something as I don't know how to do multi-threading.
Forget about the counter and use a synchronized method. Changed your method head to this:
public synchronized BufferedImage getScaledImage(byte[] imageBytes)
This lets all the threads entering the method wait until no other thread is executing the method.
If you want only a small number of threads doing the processing you can use Executor framework to have a thread pool of 10 threads. This will ensure that at one time maximum of 10 threads will be processing the requests.

How to avoid printing exception and assign another action when exception was encountered? My attempt don't work right

I am encountering an error when user doesn't type anything into input statement. I thought of using Try/Catch blocks to instead throw exception to set boolAskRepeat to true which should skip to the end of the code and repeat the loop.
This doesn't work, and I believe I'm missing something but I'm not sure what... It still throws exception saying:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at ITSLab03.main(ITSLab03.java:34)
Which is this line of code: inputStatus = input.readLine().toLowerCase().charAt(0);
What am I doing wrong here?
while (boolAskStatus == true)
{
System.out.print("Employment Status (F or P): ");
try
{
inputStatus = input.readLine().toLowerCase().charAt(0);
if (inputStatus == "f".charAt(0))
{
boolAskStatus = false;
String stringCheckSalary = null;
boolean boolCheckSalary = true;
while (boolCheckSalary == true)
{
// some code
}
outputData(inputName, inputStatus, calculateFullTimePay(inputSalary));
}
else if (inputStatus == "p".charAt(0))
{
// some code
outputData(inputName, inputStatus, calculatePartTimePay(inputRate, inputHours));
}
else boolAskStatus = true;
}
catch (IOException e) { boolAskStatus = true; }
}
You need to catch StringIndexOutOfBoundsException as well (If you observe the stack trace properly this is the exception you are getting)
catch (StringIndexOutOfBoundsException e) {
boolAskStatus = true;
}
(or)
catch Exception which catches all runtime exceptions
catch (Exception e) {
boolAskStatus = true;
}
The normal try catch pattern should look like this:
try
{
// code that is vulnerable to crash
}
catch (Specific-Exception1 e1)
{
// perform action pertaining to this exception
}
catch (Specific-Exception2 e2)
{
// perform action pertaining to this exception
}
....
....
catch (Exception exp) // general exception, all exceptions will be caught
{
// Handle general exceptions. Normally i would end the program or
// inform the user that something unexpected occurred.
}
By using .charAt(0), you are assuming that the String has a length > 0.
You could simplify this a bunch by just doing:
String entry = input.readLine().toLowerCase();
if (entry.startsWith("f")) {
...
}
else if ("entry".startsWith("p")) {
...
}
Your code doesn't work the way you want because input.readLine().toLowerCase().charAt(0) throws a StringIndexOutOfBoundsException, which is not an IOException, so the catch block never gets hit. You can make it work by changing the catch to
catch (StringIndexOutOfBoundsExceptione e) { boolAskStatus = true; }
But...
It's generally not a good idea to base your program's normal behaviour on exception handling. Think of exception throwing as something that could happen, but usually won't. Why not use something like:
final String STATUS_F = "f";
final String STATUS_P = "p";
String fromUser = null;
do {
String rawInput = input.readLine().toLowerCase();
if (rawInput.startsWith(STATUS_F)) {
fromUser = STATUS_F;
} else if (rawInput.startsWith(STATUS_P)) {
fromUser = STATUS_P;
}
} while (fromUser == null);
if (STATUS_F.equals(fromUser)) {
// do something
} else if (STATUS_P.equals(fromUser)) {
// do something else
} else {
// Shouldn't be able to get here!
throw new Exception("WTF!?");
}
It much easier for another person reading this to understand why the program loops and how the loop is controlled, in part because the code that figures out what the user is inputting and the code that decides what to do with that information are separated. Plus, you don't need to deal with exceptions.

java's executeUpdate is not working properly

I have the following java code:
if (ps.executeUpdate() != 1)
{
// Error - did not insert one row
String err = "insert unable to insert LocalUsage data: " + usg.toString();
Logger.log(err, _MODULE_CLASS, Logger.DEBUG);
throw new DaoException(err);
}
The problem if the query had a foreign key exception, then it will be thrown but it will never get to inside the if. what should I do so that it will get inside the if and output the log I have?
The problem is that this if condition is inside a try catch block, and it is going to the catch and never enters to the if condition.
executeUpdate() might throw an SQLException, as is described in its API documentation. You might want to catch that exception.
int count;
try {
count = ps.executeUpdate();
} catch (SQLException e) {
throw new DaoException("Exception while executing update: " + e.getMessage());
}
if (count != 1) {
// ...
}
As the docs states executeUpdate() may throw an exception so your code flow will fail and you will not be able to do any processing afterwards incase your exception handling is not proper.
Which I think is happening in your code right now.
While doing database call I would suggest you do it like this:
int operationStatus;
try {
operationStatus = ps.executeUpdate();
} catch(SQLException exp) {
final String message = "SQL Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} catch(Exception exp) {
final String message = "Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} finally {
//you may wish to clean up resources if they are not going to be used after this point.
}
if(operationStatus < 0) {
//Next steps
}

Return to previous position after catch statement

I have a piece of code that has a loop within a try statement. When an exception is thrown and caught, the loop is broken out of, and the execution continues along its way.. How could I get the execution to continue through the rest of the loop after the catch block is finished?
Here's a snippet of my code:
private ArrayList<URL> download(final InputStream in, URL url, int maxDepth) throws IOException {
try {
...
for (final URL link : links) {
//if exception is caught, loop will be broken here.........
download(link.openStream(), link, maxDepth - 1);
}
return alLinks;
} catch (final IOException e) {
// Display an error if anything fails.
this.searchResults.append(e.getMessage());
return null;
}
}
I'm wondering if there's any simple-minded way to slip back into right before the for loop ends, so that it can finish iterating through the rest of the elements..
Thank you very much!
Move the try-catch block into the for loop.
private ArrayList<URL> download(final InputStream in, URL url, int maxDepth) throws IOException {
...
for (final URL link : links) {
//if exception is caught, loop will be broken here.........
try{
download(link.openStream(), link, maxDepth - 1);
}
catch (final IOException e) {
// Display an error if anything fails.
this.searchResults.append(e.getMessage());
}
}
return alLinks;
}
Just put the try block within the loop:
for (...) {
try {
...
}
catch (...) {
...
}
}
I'm not sure if this has implications for runtime or anything like that, but as long as the cases in which the exception is actually thrown are rare (a.k.a. "exceptional" :-P) I wouldn't expect it to make a significant difference.

Categories

Resources