【java】异常

异常

异常的类型

1. RuntimeException

一个运行时异常发生由于编程错误。它们也称为非检查异常

这些异常不在编译时检查,而是在运行时检查。一些常见的运行时异常是:

  • API使用不当 - IllegalArgumentException

  • 空指针访问(缺少变量的初始化)- NullPointerException

  • 越界数组访问 - ArrayIndexOutOfBoundsException

  • 将数字除以0 - ArithmeticException

你可以这样想:“如果这是一个运行时异常,那就是你的错”。

如果在使用变量之前检查变量是否已初始化,则不会发生NullPointerException。
如果根据数组边界测试数组索引,则不会发生ArrayIndexOutOfBoundsException。

2. IOException

IOException也称为检查异常。它们由编译器在编译时检查,并提示程序员处理这些异常。

检查异常的一些示例是:

  • 尝试打开不存在的文件会导致 FileNotFoundException

  • 试图读取超过文件结尾的内容

异常处理

捕捉和异常处理

try {//可能会生成异常的代码放在try块中
  // 代码
  //发生异常时,它会被catch紧随其后的块捕获
} catch (ExceptionType e) { //ectch不可以单独使用和
  // 捕获块  
  //可以多个捕获块
} finally {
  //finally块
}

注意事项:

对于每个try块,只能有一个finally块。finally块是可选的。但是,如果已定义,它将始终执行(即使不会发生异常)。
如果发生异常,则在try…catch块之后执行。如果没有异常发生,则在try块之后执行。

throw和throws关键字

  • 未检查的异常:它们不是在编译时而是在运行时被检查,例如:ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException,Error类下的异常等。

  • 检查的异常:在编译时检查它们。例如IOException,InterruptedException等。

throws实例:

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    //可能产生IOException的代码
    File newFile=new File("test.txt");
    FileInputStream stream=new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try{
      findFile();
    } catch(IOException e){
      System.out.println(e);
    }
  }
}

输出结果

java.io.FileNotFoundException: test.txt (No such file or directory)

throw实例:

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("试图除以0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

输出结果

Exception in thread “main” java.lang.ArithmeticException: 试图除以0
at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
exit status 1

抛出检查异常

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    throw new IOException("文件未找到");
  }

  public static void main(String[] args) {
    try {
      findFile();
      System.out.println("try块中的其余代码");
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

输出结果

文件未找到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值