Error in Setup 2 - Cannot evaluate because of org.eclipse.debug.core.DebugException: Attempt to access illegal array index: 0

Ok, let’s try to understand what the error is trying to let us know first

Attempt to access illegal array index: 0.


Hmm, something related to accessing an illegal index in an array. As this happened when we typed in args[0], we can narrow down the “array” to being args itself. Now, on checking the args variable in VARIABLES pane in the VS Code Debug window

image

Aha! There it is, the args array is a String of size zero.

Step 1: Finding the cause of error :white_check_mark:

We found why the error was occurring. But, args shouldn’t be size zero, right?

Let’s take a step back and understand how args gets its values. We’ll start from the current function the debugger is in mainReadFile, go deeper into the methods that called this function until we find where args was populated with values.

As mainReadFile has args as its arguments, this wasn’t where args will be getting its values. Who called mainReadFile? Can you take a quick look at the stack trace again and find out the method below the PortfolioManagerApplication.mainReadFile?
image

Two probable cases are:

  1. It’s the PortfolioManagerApplication.main() method
  2. It’s PortfolioManagerApplicationTest.mainReadFile()

The error should happen only for (1). See why below

First case

image

Where does main get args?
It’s again provided as its arguments.

But, there aren’t any other methods calling the main method. Isn’t main method the first one run?

Exactly, so the args array main gets need to be passed when the PortfolioManagerApplication class is run. Are we doing it?

This won’t happen if we debug the class directly. To pass values to the main method we’ll have to pass it from the command line or call the method from a different class. But there’s a better way, see the second case :arrow_double_down:

Second case

Nb: As the PortfolioManagerApplication.mainReadFile() is called from a test, you don’t need to change anything inside the test class

If we check the test file content where it calls PortfolioManagerApplication.mainReadFile()


There it is, mainReadFile is called by passing as argument new String[]{filename}) and filename has been defined above. So, if we debug the test the handle will go to the PortfolioManagerApplication.mainReadFile() as we have set breakpoint there.