异常机制
异常机制的本质
异常的理念
异常的分类
异常的处理
try-catch-finally
throws 申明异常
try-witch-resource 新特性
百度处理异常
处理异常的步骤
百度:超级搜索
debug
可视化调试
异常机制
异常机制的本质:安度难关陈旭出现异常时程序安全的退出、处理完后继续执行的机制
异常的概念(Exception)
异常指运行过程中出现的非正常现象,例如除数为零、需要处理的文件不存在、数组下标越界等。
在java的异常处理机制中,引进了很多用来描述和处理异常的类,称为异常类。异常类定义中包含了该类异常的信息和对异常进行处理的方法。
ackage com.it.baizan;
public class Test01 {
public static void main(String[] args) {
System.out.println("111");
try{
int a = 1/0;
}catch (Exception e){//catch:捕获异常,捕获异常对象
e.printStackTrace();//打印错误信息
}
System.out.println("222");
}
}
Java是采用面向对象的方式来处理异常
【】抛出异常:
在执行一个方法时,如果发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给JRE。
【】捕获异常:
JRE得到该异常后,寻找相应的代码来处理该异常。JRE在方法的调用栈中查找,从生成异常的方法开始回溯,直到找到相应的异常处理代码为止
Error:错误,表明系统JVM已经处于不可恢复的崩溃状态中
CheckedException:编译时异常
RuntimeException:运行时异常;需要增加逻辑(判断)来处理类避免这些异常
Exception是程序本身能够处理的异常。
Exception类癌是所有类的父类,其子类对应类各种各样可能出现的异常事件
!=:不等于
package com.it.baizan;
public class Test01 {
public static void main(String[] args) {
System.out.println("111");
try{
int a = 1/0;
}catch (Exception e){//catch:捕获异常,捕获异常对象
e.printStackTrace();//打印错误信息
}
System.out.println("222");
int b = 0;//数字异常
if (b!=0){
System.out.println(1/b);
}
String str = null;//空指针异常
if (str!=null){
System.out.println(str.charAt(0));
}
}
}
CheckException已检查异常
CheckException异常的处理方式有两种:
1:使用“try/catch”捕获异常
try{
语句1;//可能出现的异常语句,如果语句之间有父类子类关系,子类在前
语句2;
语句3;
}catch(Exception1 e){
e.printStackTrace();
}catch(Exception2 e){
e.printStackTrace();
}finally{
语句4;
语句5;
}
语句6;
语句7;
try
try语句指定来一段代码,该段代码就是异常捕获并处理的范围。在执行过程中,当任意一条语句产生异常时,就会跳过该条语句中后面的代码。代码中可能会产生并抛出一种或几种类型的异常对象,它后面的catch语句要分别对这些异常做相应的处理
2:使用“throws”声明异常
package com.it.baizan;
import java.io.File;
import java.io.IOException;
//测试CheckException(已检查异常。,编译器报错)
public class Test02 {
public static void main(String[] args) throws IOException {
File file = new File("d:/a.txt");
file.createNewFile();
}
}
package com.it.baizan;
import java.io.File;
import java.util.Date;
//创建文件以及相对路径、获取项目路径
public class TestFile1 {
public static void main(String[ ] args)throws Exception{
System.out.println(System.getProperty("user.dir"));
File f = new File("a.tet");//相对路径,默认放到user.dir目录下面
f.createNewFile();//创建文件
File f2 = new File("d:/b.tet");//绝对路径
f2.createNewFile();
// 判断Fil是否存在 public boolean exists();
System.out.println("File是否存在:"+f.exists());
// 判断File是否存在目录 public boolean isDirectory() ;
//判断File是否存在文件 public boolean isFile() ;
// 返回File最后修改时间 public long lastModified();
System.out.println("File最后修改时间:"+new Date(f.lastModified()));
// 返回File大小 public long length() ;
// 返回文件名 public String getName();
// 返回文件的目录路径 public String getPath();
File f3 = new File("d:/电影/华语/大陆");
// boolean flag = f3.mkdir();//目录结构中有一个不存在,则不会创建整个目录树
// System.out.println(flag);//创建失败
boolean flag = f3.mkdirs();//目录结构中有一个不存在也没关系,创建整个目录树
System.out.println(flag);//创建成功
}
}