数组越界时跳过而不是终止程序(Java)

时间:2013-08-16 00:32:27

标签: java arrays indexoutofboundsexception

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

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)

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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

答案 2 :(得分:0)

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