简体   繁体   English

Java中引发异常

[英]Exception throws in java

I just started teaching myself java, and am currently learning how to throw exceptions. 我刚刚开始自学Java,目前正在学习如何引发异常。 The online tutorial I'm viewing says that at the SECOND bold line (list.get(i)) an exception could be caused if the value of I is less than 0 or too large. 我正在查看的在线教程说,在SECOND粗体行(list.get(i))上,如果I的值小于0或太大,可能会引起异常。 I understand how it could be too large, but how could the value be less than 0? 我知道它可能太大,但是值怎么会小于0? In what situations would this occur? 在什么情况下会发生这种情况?

private List<Integer> list;
    private static final int SIZE = 10;

    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }

    public void writeList() {
        PrintWriter out = new PrintWriter(**new FileWriter("OutFile.txt")**);

        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + **list.get(i)**);
        }
        out.close();
    }
}

All taken directly from http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html near the bottom 所有内容直接取自底部附近的http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

One example would be if you were reading off the list backwords, by starting at the end and decrementing your index. 一个示例是,如果您要从列表末尾开始并递减索引,以读取列表中的后备词。

Say you didn't set the correct condition to end your loop...This would result in a negative index and an out of bounds exception. 假设您没有设置正确的条件来结束循环...这将导致负索引和超出范围的异常。

In this specific example getting a negative index would not be possible the way you currently have your code set up. 在此特定示例中,采用当前设置代码的方式不可能获得负索引。

Example: 例:

for(int i = list.size(); i>= -1; i--){
    list.get(i);
}

In your loop, it can't. 在您的循环中,它不能。

But if you changed: 但是,如果您更改了:

for (int i = 0; i < SIZE; i++) {

to: 至:

for (int i = -1; i < SIZE; i++) {

then i will be less than 0, so list.get(i) will throw an exception. 那么i将小于0,因此list.get(i)将引发异常。

As written, your code will never encounter a negative index. 如所写,您的代码将永远不会遇到负索引。 In fact, even if the list is empty, you will never run into a case in which you will get a negative index, nor will it ever exceed the maximum capacity of your list. 实际上,即使列表为空,也永远不会遇到负索引的情况,也不会超过列表的最大容量。

This particular exception ( IndexOutOfBoundsException ) happens if you do something silly, like use a negative index to pull a value out of a list: 如果您做一些愚蠢的事情,则会发生此特定异常( IndexOutOfBoundsException ),例如使用负索引将值从列表中拉出:

list.get(-1);

...or better yet, if you step off the edge of the list (which is far more common): ...或者更好的是,如果您走出列表的边缘(这是很常见的):

list.get(SIZE); // invalid - you can only get up to SIZE - 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM