异常处理

1、异常:在程序运行的时候产生的不正常的情况

 

 

Throwable:分为Error,和Exception

 

2、异常分类:Exception

 

编译时异常:必须要进行处理    FileNotFoundException   文件找不到异常

 

运行时异常:可以不处理

 ArrayIndexOutOfBoundsException  数组角标越界

        ArithmeticException   数异常

 ClassCastException   类造型错误

       NullPointerException  空指针

3、处理异常

A 捕获异常

Try - catch   

Try-catch-catch

Try-catch-finally

Try-finally

 

4:编译时异常的处理,写代码的时候要求要进行处理,必须try-catch或者抛出

1:try-catch 自己处理,后面的代码可以执行

2throws抛给调用者,调用者可以捕获异常或者继续向上抛出,后面的代码不执行

 

 

5:运行时异常的处理:

1try-catch 捕获异常,自己解决

2throws:抛出异常,这个是写在方法声明后面,抛给调用者,调用者可以捕获,可以继续抛出

3throw:抛出异常,这个是写在方法体中。


6、自定义异常:

1:自己定义一个类继承Exception ,命名一般是xxxException

2:添加一个构造器

3:在另外一个类抛出自定义异常

4:在测试类里面捕获异常

 

7、File:掌握常用方法就可以

  // 创建一个file对象。将路径封装在这个对象中

File file = new File("c:/aa.txt");

// 判断文件是否存在

if (!file.exists()) {

try {

// 如果不存在,就创建

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

 

       String name = file.getName();

 System.out.println(name);

 boolean b1 = file.canRead();

 System.out.println(b1);

 System.out.println(file.length());

 System.out.println(file.getAbsolutePath());

 System.out.println(file.getParent());

原文地址:https://www.cnblogs.com/future-zmy/p/6087459.html