- Java程序运行过程中的异常事件可分为:
- 错误(Error:JVM系统内部错误、资源耗尽等严重情况
- 异常(Exception:其他因编译程序错误或偶然的外在因素导致的一般性问题
集中常见的异常:
- 空指针访问
- 视图读取不存在的文件
- 数组越界异常
- 网络中断异常
异常捕获
- try-catch来捕获异常
- 一个try可以多个catch配合使用
- 不需要捕获异常的代码可以放在try-catch中,也可以不放
- 代码块中抛出哪个异常,就执行异常对应的代码块,对视对应的catch
- finally无论如何都会执行
try{
//可能抛出异常的代码块
}catch(Exception e){
//如果异常被抛出,则执行这段代码
}catch(ExceptionType e){
//如果另外的异常被抛出,则执行这段代码
}【finally{
//无条件执行的语句
}】
例子:
package org.example.面向对象;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Exp {
public static void test(){
try{
int[] arr={1,2,3};
System.out.println(arr[2]);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("finally");
}
System.out.println("--------------");
}
public static void test2(){
FileInputStream fileInputStream=null;
try{
String filePath="D://a.txt";
fileInputStream=new FileInputStream(filePath);
byte[] bytes=new byte[1024];
while (fileInputStream.read(bytes)!=-1){
}
fileInputStream.close();
}catch (FileNotFoundException e){
e.printStackTrace();
System.out.println("------------------");
}catch (IOException e){
e.printStackTrace();
System.out.println("--------------------");
}finally {
System.out.println("finally");
}
}
public static void main(String[] args){
test();
test2();
}
}