ArrayIndexOutOfBoundsException()

ArrayIndexOutOfBoundsException(int index)

ArrayIndexOutOfBoundsException(String s);

ArrayIndexOutOfBoundsException 可以 new 对象,有构造方法,就可以 new 对象。创建对象,如果遇到问题就抛出, new ArrayIndexOutOfBoundsException(index) 。

如何抛出呢?利用关键字 throw ,出现异常,在 Java 虚拟机, jvm 中需要把问题抛出,给调用者 main ,主函数收到抛出的异常对象,但主函数没有办法处理,继续抛出调用者 jvm , jvm 收到异常问题后,将异常信息显示在屏幕上。

异常概述(意外、例外)


什么是异常呢?常见:

try-catch-finally
// try-catch-finally
public void method(){
try {
// 代码段
// 产生异常的代码段
}catch (异常类型 ex) {
// 对异常进行处理的代码段
}finally{
// 代码段
}
}
throw
throws
try-catch-finally
// try-catch-finally
public void method(){
try {
// 代码段
// 产生异常的代码段
}catch (异常类型 ex) {
// 对异常进行处理的代码段
}finally{
// 代码段
}
}
throw
throws

throws 声明时要进行抛出的异常

throw 要手动将产生的异常抛出

public void method() throws Exception1,Exception2,…,ExceptionN {
// 产生异常代码
}
// throw new IOException();
// 自己抛出的问题自己进行异常解决。
// 在抛出异常处,通过throws关键字标明异常类型
public void method() throws 异常类型{
// 代码 抛出
throw new 异常类型();
}
自定义异常
异常链

异常处理分类为:

  1. 抛出异常
  2. 捕捉异常

简单案例

public class Test{
public static void main(String[] args){
try{
String msg = redText(“C:\\\\a.txt”);
}catch(PathNotExistException e){
// 进行处理
}
}
}

Throwable异常的顶级父类

异常 Exception 处理方式有两种,一为 捕获 ,二为 继续抛出编译时的异常 。

RuntimeException 运行时异常,只有在运行的时候才会出现,可以处理,也可以不处理。

自定义异常,可以自己定义异常,自己定义一个类,如果这个类继承某个异常类,继承的是 Exception 或其他异常,即定义了一个 编译时异常 ,如果继承的是运行时异常 RuntimeException或是它的子类,就定义了一个 运行时异常 。

Throwable 类是 Java 中所有错误或异常的超类,只有当对象是这个类的实例时,能通过虚拟机或是 Java 中 throw 语句抛出。

Exception分为两大类

  1. 非检查异常( Unchecked Exception ):编译器不要求强制处理异常
  2. 检查异常( Checked Exception ):编译器要求必须处理的异常,如 IO 异常等

捕获异常

try

catch

finally

声明异常,抛出异常

throws

throw

如果某方法出现了异常,却是没有能力的处理,可以在方法处用 throws 来声明抛出异常,谁调用这个方法,谁就去处理这个异常。

public void method() throws Exception1,Exception2,…,ExceptionN {

// 异常的代码

}

Java中的异常处理情况

JAVA 异常

try...catch...finally 结构的使用方法

class Test{
public static void main(String args[]){
try{
int i = 1 / 0;
}
catch(Exception e){
e.printStackTrace();
}
finally{
System.out.println(“finally”);
}
System.out.println(5);
}
}
class Test{
public static void main(String args[]){
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
}
}

throw 和 throws 的作用区别:

class Person{
private int age;
public void setAge(int age) throws Exception{
if(age<0){
RuntimeException e = new RuntimeException(“年龄不能小于0”);
throw e;
}
this.age = age;
}
}
class Test{
public static void main(String args[]){
Person person = new Person();
try{
person.setAge(-1);
}
catch(Exception e){
System.out.println(e);
}
}
}

Erro



  • Error 是 Throwable 的子类,用于标记严重错误
  • Exception 是 Throwable 的子类,指示合理的程序想去 catch 的条件,非严重错误

try/catch的执行过程


如果出现异常,系统则会抛出一个异常,