Java—异常的理解与处理机制、File类

Java—异常的理解与处理机制、File类

1、异常的理解与分析

Throwable包含了错误(Error)和异常(Exception两类)
  Exception又包含了运行时异常(RuntimeException, 又叫非检查异常)和非运行时异  
常(又叫检查异常)
  (1) Error是程序无法处理了, 如果OutOfMemoryError、OutOfMemoryError等等,  
这些异常发生时, java虚拟机一般会终止线程 .
  (2) 运行时异常都是RuntimeException类及其子类,如 NullPointerException、  
IndexOutOfBoundsException等, 这些异常是不检查的异常, 是在程序运行的时候可能  
会发生的, 所以程序可以捕捉, 也可以不捕捉. 这些错误一般是由程序的逻辑错误引起的,   
程序应该从逻辑角度去尽量避免.
  (3) 检查异常是运行时异常以外的异常, 也是Exception及其子类, 这些异常从程序的  
角度来说是必须经过捕捉检查处理的, 否则不能通过编译. 如IOException、  
SQLException等
两者的区别

    非检查异常表示无法让程序恢复运行的异常,导致这种异常的原因通常是由于执行了错  
误的操作。一旦出现错误,建议让程序终止。
    受检查异常表示程序可以处理的异常。如果抛出异常的方法本身不处理或者不能处理  
它,那么方法的调用者就必须去处理该异常,否则调用会出错,连编译也无法通过。
    对于运行异常,建议不要用 try...catch...捕获处理,应该在程序开发调试的过程  
中尽量的避免,当然有一些必须要处理的,自己知道了那个部分会出现异常,而这种异常你要  
把它处理的你想要的结果,例如:空值处理。

代码展示:

package com.hwadee;
/**
 * 编译期异常,如果不处理,就没有办法运行。
 * 编译期异常:1、throws   2、try{}catch(异常类型  名字){}finally{释放资源的}
 * try:里面放的是可能出现问题的代码。最好里面少放代码,精确地放代码---->哪些代码有可能出错才放进去
 * catch:推荐的做法是,里面要有东西。哪怕仅仅是一句提示。
 * finally特点:里面的总是会执行,不管try里面是够报错。所以,它通常用于释放资源。
 */
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class TestException1 {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }
    public static void test1() {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        System.out.println(time);
        System.out.println("---------------------");

        try {     //编译期异常,
            java.util.Date parseDate = simpleDateFormat.parse(time);
            System.out.println(parseDate);
        } catch (ParseException e) {
            System.out.println("出错了!!!");
            e.printStackTrace();
        }
    }
    public static void test2() {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);

        try {
            Date parsedDate = simpleDateFormat.parse(time);
            System.out.println("这是一句代码");
        } catch (ParseException e) {
            System.out.println("出错了!!!!!");
            //e.printStackTrace();
        }

        System.out.println("这是try catch 之外的语句");

    }
    public static void test3() {
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        //声明了系统资源
        try {
            Date parsedDate = simpleDateFormat.parse(time);
            System.out.println("这是一句代码");
            System.out.println("这一句也不执行");
            System.out.println("如果我在这里使用了系统资源");
            System.out.println("使用完之后,释放系统资源;否则太耗费机子");
            //System.exit(0);
        } catch (ParseException e) {
            System.out.println("出错了!!!!!");
            //e.printStackTrace();
        } finally {
            System.out.println("这里是finally里面的语句");
        }

        System.out.println("这是try catch 之外的语句");

    }

}

这里写图片描述
2、throw与throws使用

   throws的方式处理异常:定义功能方法时,需要把出现的问题暴露出来让调用者去处理。  
那么就通过throws在方法上标识。
   throw的概述:在功能方法内部出现某种情况,程序不能继续运行,需要进行跳转时,就  
用throw把异常对象抛出。
throw与throws的区别:
    throws:用在方法声明后面,跟的是异常类名。可以跟多个异常类名,用逗号隔开。表  
 示抛出异常,由该方法的调用者来处理。
    throw:用在方法体内,跟的是异常对象名。只能抛出一个异常对象名。表示抛出异常,  
 由方法体内的语句处理。

代码展示:

package com.hwadee;

/**
 * throws ParseException
 * 
 * throws + 异常类名
 * 
 * 谁调用方法,那么就将异常抛给谁。 在实际开发中,抛给jvm,是不理智的行为,没有意义,不推荐这么做。
 * 
 * 在教学当中仅仅是为了方便而已,才这么干。
 *
 */
public class TestException2 {

    public static void main(String[] args) {
//      test1();
//      test2();
        test3();
//      test4();
//      test5();
    }
    /*
     * finally:被finally控制的语句体一定会执行
     * 注意:如果在执行到finally之前jvm退出了,就不能执行了。
     * 
     * A:格式
     *      try...catch...finally...
     * B:用于释放资源,在IO流操作和数据库操作中会见到
     */
    public static void test1() {
        int a = 3;
        int b = 0;
        if (b != 0) {
            int result = a / b;
            System.out.println(result);
        } else {
            System.out.println("今天天气不是很好");
        }
    }

    public static void test2() {

        try {
            System.out.println(3 / 0);
        } catch (ArithmeticException e) {
            System.out.println("报了一个错误");
        } finally {
            System.out.println("finally");
        }
    }

    public static void test3() {
        try {
            int result = 3 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 的异常");
        } finally {
            System.out.println("这里释放资源!!!");
        }

        try {
            int a[] = { 1, 2, 3 };
            System.out.println(a[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException 的异常");
        } finally {
            System.out.println("这里释放资源!!!");
        }
    }

    public static void test4() {
        try {

            int a[] = { 1, 2, 3 };
            System.out.println(a[3]);
            System.out.println("------");
            int result = 3 / 0;
            System.out.println(result);

        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 的异常");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException 的异常");
        } finally {
            System.out.println("这里释放资源!!!");
        }

    }

    public static void test5() {
        try {

            int a[] = { 1, 2, 3 };
            System.out.println(a[3]);
            System.out.println("------");
            int result = 3 / 0;
            System.out.println(result);

        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 的异常");
        } catch (RuntimeException e) {
            System.out.println("RuntimeException 的异常");
        } finally {
            System.out.println("这里释放资源!!!");
        }

    }
}

这里写图片描述

package com.hwadee;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestException3 {

    public static void main(String[] args) throws ParseException {
        test1();
    }
    public static void test1() throws ParseException {
        test2();
    }

    public static void test2() throws ParseException {
        Date date = new Date();
        System.out.println(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        System.out.println(time);
        Date parsedDate = simpleDateFormat.parse(time);
        System.out.println(parsedDate);

    }

}

这里写图片描述

package com.hwadee;
/*
 * throw:如果出现了异常情况,我们可以把该异常抛出,这个时候的抛出的应该是异常的对象。
 * 
 * throws和throw的区别(面试题)
 *  throws
 *      用在方法声明后面,跟的是异常类名
 *      可以跟多个异常类名,用逗号隔开
 *      表示抛出异常,由该方法的调用者来处理
 *      throws表示出现异常的一种可能性,并不一定会发生这些异常
 *  throw
 *      用在方法体内,跟的是异常对象名
 *      只能抛出一个异常对象名
 *      表示抛出异常,由方法体内的语句处理
 *      throw则是抛出了异常,执行throw则一定抛出了某种异常
 *   编译期异常的抛出
 *   在方法声明上抛出,是为了告诉调用者,你注意了,我有问题。
 */
public class TestException4 {

    public static void main(String[] args) {
//      method();

        try {
            test2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void test1() {
        int a = 10;
        int b = 0;
        if (b == 0) {
            throw new ArithmeticException();
        } else {
            System.out.println(a / b);
        }
    }

    public static void test2() throws Exception {
        int a = 10;
        int b = 0;
        if (b == 0) {
            throw new Exception();
        } else {
            System.out.println(a / b);
        }
    }
}

这里写图片描述
3、多个异常的处理
根据代码进行理解:

package com.hwadee;

/*
 * A:一个异常
 * 
 * B:二个异常的处理
 *      a:每一个写一个try...catch
 *      b:写一个try,多个catch
 *          try{
 *              ...
 *          }catch(异常类名 变量名) {
 *              ...
 *          }
 *          catch(异常类名 变量名) {
 *              ...
 *          }
 *          ...
 * 
 *          注意事项:
 *              1:能明确的尽量明确,不要用大的来处理。
 *              2:平级关系的异常谁前谁后无所谓,如果出现了子父关系,父必须在后面。
 * 
 * 注意:
 *      一旦try里面出了问题,就会在这里把问题给抛出去,然后和catch里面的问题进行匹配,
 *      一旦有匹配的,就执行catch里面的处理,然后结束了try...catch
 *      继续执行后面的语句。
 */
public class TestException5 {

    public static void main(String[] args) {
        // test1();

        // test2();

        // test3();

        test4();
    }

    // 一个异常
    public static void test1() {
        int a = 10;
        int b = 0;
        try {
            System.out.println(a / b);
        } catch (ArithmeticException ae) {
            System.out.println("除数不能为0");
        }
        // 第二阶段
        System.out.println("over");
    }

    // 两个异常
    public static void test2() {
        int a = 10;
        int b = 0;
        try {
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        }

        int[] arr = { 1, 2, 3 };
        try {
            System.out.println(arr[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        }
        System.out.println("over");
    }

    // 两个异常的处理
    public static void test3() {
        int a = 10;
        int b = 0;
        int[] arr = { 1, 2, 3 };

        try {
            System.out.println(arr[3]);
            System.out.println(a / b);
            // System.out.println(arr[3]);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        }

        System.out.println("over");
    }

    public static void test4() {
        int a = 10;
        int b = 0;
        int[] arr = { 1, 2, 3 };

        // 爷爷在最后
        try {
            System.out.println(a / b);
            System.out.println(arr[3]);
            System.out.println("这里出现了一个异常,怎么办?");
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        } catch (Exception e) {
            System.out.println("出问题了");
        }

        // 爷爷在前面的情况
        // try {
        // System.out.println(a / b);
        // System.out.println(arr[3]);
        // System.out.println("这里出现了一个异常,怎么办?");
        // } catch (Exception e) {
        // System.out.println("出问题了");
        // } catch (ArithmeticException e) {
        // System.out.println("除数不能为0");
        // } catch (ArrayIndexOutOfBoundsException e) {
        // System.out.println("你访问了不该的访问的索引");
        // }

        System.out.println("over");
    }
}

这里写图片描述
4、File类的概述以及使用

   File类主要是完成了文件夹管理的命名、查询、文件属性和处理目录等到操作它不进行  
文件夹内容的读取操作。
   File更应该叫做一个路径,文件路径或者文件夹路径,路径分为绝对路径和相对路径,  
绝对路径是一个固定的路径,从盘符开始,相对路径相对于某个位置,在ecplise下是指当  
前项目下,在dos下,查看API指的是当前路径,文件和目录路径名的抽象表示形式。

代码展示:

package com.hwadee;

import java.io.File;
import java.io.IOException;

public class TestFile1 {

    public static void main(String[] args) throws IOException {
        file1();
        file2();
        file3();
        file4();
        file5();
        file6();
        file7();
        file8();
        file9();
        file10();
        file11();
    }
    //新建文件
    public static void file1() throws IOException {
        File file=new File("D:\\132.txt");
        boolean isSuc = file.createNewFile();
        System.out.println(isSuc);
    }
    //删除文件
    public static void file2() throws IOException {
        File file=new File("D:\\111");
        boolean isSuc = file.delete();
        System.out.println(isSuc);
    }
    //新建文件夹
    public static void file3() throws IOException {
        File file=new File("D:\\100\\456");
        boolean isSuc = file.mkdirs();
        System.out.println(isSuc);
    }
    //删除文件夹,若文件夹中存在文件夹,必须先删除里面的文件夹,才能删除总文件夹
    public static void file4() throws IOException {
        File file=new File("D:\\100");
        boolean isSuc = file.delete();
        System.out.println(isSuc);
    }
    //重命名文件夹
    public static void file5() throws IOException {
        File fileO=new File("D:\\100");
        File fileT=new File("D:\\hhh");
        boolean isSuc = fileO.renameTo(fileT);
        System.out.println(isSuc);
    }
    //判断是否是文件夹
    public static void file6() throws IOException {
        File fileO=new File("D:\\hhh");
        boolean isSuc = fileO.isDirectory();
        System.out.println(isSuc);
    }
    //判断是否可读
    public static void file7() throws IOException {
        File fileO=new File("D:\\hhh");
        boolean isSuc = fileO.canRead();
        System.out.println(isSuc);
    }
    //判断是否可写
    public static void file8() throws IOException {
        File fileO=new File("D:\\hhh");
        boolean isSuc = fileO.canWrite();
        System.out.println(isSuc);
    }
    //判断是否是文件
    public static void file9() throws IOException {
        File fileO=new File("D:\\132.txt");
        boolean isSuc = fileO.isFile();
        System.out.println(isSuc);
    }
    //判断是否存在
    public static void file10() throws IOException {
        File fileO=new File("D:\\132.txt");
        boolean isSuc = fileO.exists();
        System.out.println(isSuc);
    }
    //判断是否隐藏
    public static void file11() throws IOException {
        File fileO=new File("D:\\hhh");
        boolean isSuc = fileO.isHidden();
        System.out.println(isSuc);
    }
}

这里写图片描述

package com.hwadee;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestFile2 {

    public static void main(String[] args) {
        file1();
        file2();
        file3();
        file4();
    }
    //length的单位是字节
    //getname返回的包括了文件名和后缀名
    //lastModified  最后修改文件的时间
    public static void file1() {
        File file1=new File("D:\\英雄时刻\\qqq.txt");
        long length = file1.length();
        System.out.println(length);
        String name = file1.getName();
        System.out.println(name);
        long time = file1.lastModified();
        System.out.println(time);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date(time));
        System.out.println(format);
    }
    public static void file2() {
        File file1=new File("D:\\课程");
        String[] list = file1.list();
        for(String s:list) {
            System.out.println(s);
        }
    }
    public static void file3() {
        File file1=new File("D:\\课程");
        File[] listFiles = file1.listFiles();
        for(int i=0;i<listFiles.length;i++) {
            File f=listFiles[i];
            System.out.println(f.getName());
        }
    }
    public static void file4() {
        String separator = File.separator;
        System.out.println(separator);

        File file1=new File("D:\\hhh");
        System.out.println(file1.getAbsolutePath());
        file1=new File("D:"+File.separator+"hhh");
        System.out.println(file1.getAbsolutePath());
    }
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值