Click here to Skip to main content
15,881,630 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can anyone help in solving this exception pls.
The below code will help me in getting the time stamp from a file, if the required string "Stopping Component"is present in it.

Java
private String[] startTime(String [] startTime) throws Exception {
		try {
			String Log = Log(); /// this is a method which will read a file
			String [] columns = Log.split(" ");
			String [] startTime1 = new String [3] ;
			int j = 0;
			for (int i= 0; i < Log.length(); i++) {
				if (columns[i].contains("Stopping") && columns[i+1].contains("Component")) {
					startTime1[j] = columns[i+2];

					System.out.println("The start time in method "  + startTime1[j]);
					j++;
				}
			}
			
			return startTime1;
		} catch (Exception e) {
			System.out.println(" exception occurred" + e );
			return null;
		}

	}



when ran I am getting the below exception..I see that the two time stamps are fetched.. but i got the outOfBoundsException.

I found from the net that this exception will occur when we try to access illegal index of an array. But I am unable to see what is that here in above code. Please guide me

output:
The start time in method 05:32:17.516
The start time in method 05:32:23.242
exception occurred java.lang.ArrayIndexOutOfBoundsException: 1854443
Posted
Updated 13-Oct-15 20:57pm
v4
Comments
Member 12018498 15-Oct-15 1:42am    
Thank you so much for suggesting. I will improvise my code. And ppolymorphe suggestion solved my problem :)

How do you know that when startTime1[j], j is always below 3 ?
How do you know that columns[i+2] always exist ?
You loop on i which is bounded to the size of log, but in the loop you access to columns element without knowing the size.

You should try the debugger to see what is doing your code.
 
Share this answer
 
Comments
Member 12018498 15-Oct-15 1:38am    
Thank you for suggestion. Yes I know that j is always below 3, because the string 'log' which reads the file has only 2 time occurrence of substing "stopping component". You are right.I found out the mistake. I changed i < Log.length() to i < coulmns.lenght. Its working now.
Why not try defensive coding. I believe the variable j can cause the illegal index which means at some point the code is trying to access startTime1[3] which is not present in memory and unfortunately Java will throw exception.Also i+2 has the potential to access index out of bounds.

My advice would be to use and if statement

Java
if(j<3 && i<log.length()-2)>   startTime1[j] = columns[i+2];
}


Hope this solves you problem.....

PS.- Do not use Strings they are immutable use StringBuilder or StringBuffer if you want thread safe....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900