-1

当数组超出范围时,有没有办法跳过当前命令?

memory[count] = allProcesses[processIndex[index]+temp];

当数组试图访问一个不存在的变量时,它会越界。我只想打印一条错误消息并继续运行,但每次发生时,程序都会终止

我试过的:

try {
    memory[count] = allProcesses[processIndex[index]+temp];
    } catch (Exception e) {
        System.out.println("Page Fault");
        Thread.sleep(2000);
        }

这是错误消息:

...
Adding Process 10, address 48214, page 1868, offset 12, value 550 to memory location 54
Adding Process 11, address 30649, page 557, offset 13, value 229 to memory location 55
Adding Process 11, address 46819, page 343, offset 7, value 519 to memory location 56
Adding Process 11, address 54762, page 94, offset 14, value 425 to memory location 57
Page Fault
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 726384
    at MMU.MMUProcess(MMU.java:58)
    at Driver.main(Driver.java:73)
4

3 回答 3

2

如果您在捕获异常时以下代码中存在异常,我确信程序不会终止:

try {
    memory[count] = allProcesses[processIndex[index]+temp];
    } catch (Exception e) {
        System.out.println("Page Fault");
        Thread.sleep(2000);
        }

我相信在此代码之上或之下还有一些其他代码,它们未封装在 try/catch 下并引发 ArrayIndexOutOfBound 异常。

于 2013-08-16T00:46:44.377 回答
0

导致终止的是 mmu.java:58 处未捕获的异常,尝试捕获该行并打印堆栈跟踪,这应该有助于解决问题。

于 2013-08-16T00:54:58.447 回答
0

我怀疑它会因另一个原因而终止。例如,这段代码:

class Example {
    public static void main(final String[] args) {
        int[] array = new int[3];
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        try {
            array[3] = 4;
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("I didn't die");
    }
}

产生这个输出:

java.lang.ArrayIndexOutOfBoundsException: 3
I didn't die
于 2013-08-16T00:46:44.313 回答