干扰程序正常流程的意外、不需要的事件称为Exception 。
大多数时候异常是由程序引起的,并且这些异常是可以恢复的。示例:如果程序要求在运行时从远程文件中读取数据,如果远程文件不可用,那么将得到 RuntimeException
说 fileNotFoundException
。如果发生 fileNotFoundException
,可以将本地文件提供给程序以正常读取并继续程序的其余部分。
java中主要有 两种类型的异常如下:
1.检查异常:
编译器为了程序在运行时的顺利执行而检查的异常称为检查异常。在我们的程序中,如果有可能出现检查异常,那么必须处理该检查异常(通过 try-catch 或 throws 关键字),否则将得到编译时错误;
检查异常的示例有ClassNotFoundException 、 IOException 、 SQLException等 。
2.未经检查的异常:
未经编译器检查的异常,无论程序员是否处理此类异常,都称为未经检查的异常。
未经检查的异常的示例有ArithmeticException、ArrayStoreException等。
仅当在编译时不可能发生任何异常时,才会检查或未检查异常是否在运行时发生每个异常。
ArrayIndexOutOfBoundException
ArrayIndexOutOfBoundException 是 RuntimeException 的子类,因此它是一个未经检查的异常。每当我们使用负值或大于或等于给定数组长度的值作为数组的索引时,JVM 都会自动引发此异常,开发者将得到此异常。
示例:
// Java program to demonstrate the
// ArrayIndexOutOfBoundException
// import the required package
import java.io.*;
import java.lang.*;
import java.util.*;
// driver class
class YiibaiDemo {
// main method
public static void main(String[] args)
{
// declaring and initializing an array of length 4
int[] x = { 1, 2, 3, 4 };
// accessing the element at 0 index
System.out.println(x[0]);
// accessing an index which is greater than the
// length of array
System.out.println(x[10]);
// accessing a negative index
System.out.println(x[-1]);
}
}
StringIndexOutOfBoundException
StringIndexOutOfBoundException
是 RuntimeException
的子类,因此它是一个未经检查的异常。每当在字符串类方法中使用负数或大于或等于给定字符串长度的索引值时,JVM 都会自动引发此异常。
例子:
// Java program to demonstrate
// StringIndexOutOfBoundException
// import required packages
import java.io.*;
import java.util.*;
// driver class
class YiibaiDemo {
// main class
public static void main(String[] args)
{
// declaring a string
String s = "YIIBAIFORGEEKS";
// accessing the second character of the given
// string using charAt() method
System.out.println(s.charAt(1));
// now using an index greater than the length of the
// string
System.out.println(s.charAt(30));
}
}
ArrayIndexOutOfBoundException 异常 | StringIndexOutOfoundExcetion 异常 |
---|---|
抛出它表示已使用非法索引访问数组(即索引值是负数或大于或等于数组的长度)。 | 它由 string 类的方法抛出,指示 string 方法中使用的索引值是负数或大于或等于给定字符串的长度。 |