Java:异常

2023-05-20  本文已影响0人  iOS_修心

JVM 处理方式
1.把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
2.程序停止执行

1.异常体系

2.编译时异常和运行时异常

3:throws方式处理异常

4:throw抛出异常

throw new 异常();

5 try-catch方式处理异常

4.8 Throwable成员方法(应用)

   public static void main(String[] args) {
        System.out.println("开始");
        method();
        System.out.println("结束");
    }

    public static void method() {
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
            System.out.println("这里能够访问到吗");
        } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
            // 返回此 throwable 的详细消息字符串
            System.out.println(e.getMessage());

            // 返回此可抛出的简短描述
            System.out.println(e.toString());

            //把异常的错误信息输出在控制台
            e.printStackTrace();

        }
    }

9:自定义异常

10:finally

用来创建在 try 代码块后面执行的代码块。无论是否发生异常,finally 代码块中的代码总会被执行。在 finally 代码块中,可以运行清理类型等收尾善后性质的语句

try{
  // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}finally{
  // 程序代码
}
public class ExcepTest{
  public static void main(String args[]){
    int a[] = new int[2];
    try{
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
    }
    finally{
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
    }
  }
}

11:try-with-resources

try (resource declaration) {
  // 使用的资源
} catch (ExceptionType e1) {
  // 异常块
}

try 用于声明和实例化资源,catch 用于处理关闭资源时可能引发的所有异常。

public class RunoobTest {

    public static void main(String[] args) {
    String line;
        try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
            while ((line = br.readLine()) != null) {
                System.out.println("Line =>"+line);
            }
        } catch (IOException e) {
            System.out.println("IOException in try block =>" + e.getMessage());
        }
    }
}

我们实例一个 BufferedReader 对象从 test.txt 文件中读取数据。
在 try-with-resources 语句中声明和实例化 BufferedReader 对象,执行完毕后实例资源,不需要考虑 try 语句是正常执行还是抛出异常。
如果发生异常,可以使用 catch 来处理异常。

上一篇 下一篇

猜你喜欢

热点阅读