知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

    • 扩展

    • IO & Stream

    • Error & Exception

      • Theory:Errors in programs
      • Theory:What is an exception
      • Theory:NPE
      • Theory:Array exceptions
        • NullPointerException
        • NegativeArraySizeException
        • ArrayIndexOutOfBoundsException
        • Conclusion
      • Theory:Hierarchy of exceptions
      • Theory:Exception Handling
      • Theory:Throwing exceptions
      • Theory:Cutom exceptions
      • Theory:What is a bug
      • Theory:Introduction to logging
      • Theory:Debugging techniques
    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • Error & Exception
Jim
2022-07-09
目录

Theory:Array exceptions

No wonder that different types of exceptions may occur when your program processes an array. To avoid them, you should be aware of the situations where you are at risk of having one and stick to a set of commonly used practices. Now let's learn what exactly we are dealing with here.

# NullPointerException

As you probably know by now, an array is a reference type, which means its variable can be null , and that may lead to NPE.

int[] numbers = null;
int size = numbers.length; // It throws NPE
1
2

We will not dwell on this since we suppose that you are already familiar with NPE and how to avoid it by using additional checks in your code:

int size = numbers == null ? 0 : numbers.length;
1

# NegativeArraySizeException

If you try to create an array with a negative size, your code will compile successfully, but this line will throw NegativeArraySizeException while executing.

int negSize = -1;
int[] numbers = new int[negSize]; // an exception here
1
2

It's not very likely that you'll face this exception as a developer, but it makes sense to keep it in mind. To avoid it, simply do not use variables that can have a negative size when setting the size of an array.

An array may have a size greater than or equal to zero. If this is the case, the code will compile successfully and will not throw NegativeArraySizeException at runtime.

# ArrayIndexOutOfBoundsException

This is a fairly common exception that occurs while working with arrays. It is caused by attempting to access a non-existent element of the array.

int[] array = { 1, 2, 3 }; // an array of ints

int n1 = array[2]; // n1 is 3
int n2 = array[3]; // Exception
1
2
3
4

In this code, the last line produces ArrayIndexOutOfBoundsException since the last index of the array in question is 2.

The code will throw the same exception if we try to access an element with a negative index:

array[0];  // OK
array[-1]; // Exception
1
2

Since a string can be considered as a sequence of characters, a similar exception may occur when accessing a non-existing element of a string. It is called StringIndexOutOfBoundsException.

To avoid the ArrayIndexOutOfBoundsException, we may check if the given index belongs to the interval [0, length – 1].

For example, let's take a look at a program, displaying an element of the array by the index, provided in the input. If the index is out of bounds, the program prints a message instead of throwing an exception.

public class NoIndexOutOfBoundsExceptions {

    public static void main(String[] args) {
        int[] hardCodedArray = { 3, 2, 4, 5, 1 };

        Scanner scanner = new Scanner(System.in);

        int index = scanner.nextInt();

        if (index < 0 || index > hardCodedArray.length - 1) {
            System.out.println("The index is out of bounds.");
        } else {
            System.out.println(hardCodedArray[index]);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Here are some possible inputs and the corresponding outputs of the program:

  • the index is 0, the program outputs "3";
  • the index is 1, the program outputs "2";
  • the index is 4, the program outputs "1";
  • the index is -1, the program outputs "The index is out of bounds.";
  • the index is 5, the program also outputs "The index is out of bounds.".

That is how we can avoid ArrayIndexOutOfBoundsExceptions by using a conditional statement and the length property of an array.

# Conclusion

We have considered three types of array exceptions:

  • NullPointerException;
  • NegativeArraySizeException which you may face when you are creating an array with a negative size;
  • ArrayIndexOutOfBoundsException which occurs when you try to access a non-existent element.

As a developer, you need to keep in mind what exceptions you may face and, of course, basic ways to avoid them.

编辑 (opens new window)
#Java#Array#Exception
上次更新: 2022/09/26, 16:55:15
Theory:NPE
Theory:Hierarchy of exceptions

← Theory:NPE Theory:Hierarchy of exceptions→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式