What is the different between a stackoverflow and arrayindexoutofbounds?
It seems like in reality these should be almost identical. You are refer开发者_Python百科encing or sticking data where it shouldn't go.
StackOverflowError
occurs during endless recursive calls. It has nothing to do with arrays. ArrayIndexOutOfBoundsException
occurs when when you try to use an index beyond the size of the array.
StackOverFlowError: Occurs when the JVM (Java Virtual Memory) is running out of allocated heap space.
ArrayIndexOutOfBoundsException: Occurs when an application tries to access the array index which does not fall in declared range.
These two are actually very different things. As the other guys have already mentioned, ArrayIndexOutOfBoundsException is an Exception that occurs when you are trying to access an array using an incorrect index. This could be caused by a very simple bug in programming logic.
StackOverflowError is something more low-level. It has nothing to do with arrays and, contrary to what the other guys said, has nothing to do with the heap either. Try doing that trick with a List and you'll get an OutOfMemoryError instead. Now it's an Error that is much more similar to StackOverflowError than ArrayIndexOutOfBoundsException. Both OutOfMemoryError and StackOverflowError indicate that you're running out of memory, only in different segments. Running out of stack memory almost always occurs due to infinite recursion (unless you have a ridiculously long chain of methods calling each other with lots of local variables in them), and running out of heap memory happens when you allocate too much and keep all those references so even the garbage collector can't free some memory for you.
So when ArrayIndexOutOfBoundsException is indeed "sticking data where it shouldn't go", StackOverflowError and OutOfMemoryError are better described as "running out of memory to stick your data into".
arrayindexoutofbounds : The exception that is thrown when an attempt is made to read beyond the bounds of an array.
stackoverflow : An error that is issued when a stack overflow occurs.
Arrayindexoutofbounds: You limit your variable for example defining an array with size of 50 and if you want to use the 51. element of that array you get this exception.
Stackoverflow: Think about that you didn't limit your variable for example;
List myList = new List();
And you are adding elements to this list.
myList.add(something);
If you add too much element that your heap memory can't allocate any more space to keep your variable it throws that exception.
At first your limit is 50, at 51 you get an exception, at second you don't get an exception at 51. element if your heap is free enough but you can get an exception when your heap not enough for you.
精彩评论