码迷,mamicode.com
首页 > 其他好文 > 详细

23、异常、File类(构造方法、创建、删除)

时间:2020-05-23 18:19:52      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:遇到   容量   inter   return语句   ann   jvm   data   mat   特殊   

异常

异常的继承体系

技术图片

JVM默认处理运行期异常

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/23 10:12
 */
public class MyTest {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3};
        System.out.println(arr[3]);
        System.out.println(arr[0]);
        /*
        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
            at org.westos.demo.MyTest.main(MyTest.java:10)

        Process finished with exit code 1
         */
        
        /*
        jvm默认处理运行期异常:打印异常的堆栈信息,并停止执行后续的代码。
         */
        
        /*
        public
        class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException {}
        public
        class IndexOutOfBoundsException extends RuntimeException {}
         */
    }
}

异常的处理方式

  • throws
  • try-catch-finally

try-catch处理单个异常

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/23 10:36
 */
public class MyTest2 {
    public static void main(String[] args) {
        //System.out.println(10 / 0);

        /*
        Exception in thread "main" java.lang.ArithmeticException: / by zero
	        at org.westos.demo.MyTest2.main(MyTest2.java:9)

        Process finished with exit code 1 进程异常终止
         */

        try {
            //try代码块存放有可能发生异常的代码
            System.out.println(10 / 0);
        } catch (RuntimeException e) {
            //catch代码块存放异常的处理方式
            e.printStackTrace();
        }
        System.out.println("try-catch成功,程序即使发生异常依然可以执行后续代码。");

        /*
        java.lang.ArithmeticException: / by zero
	        at org.westos.demo.MyTest2.main(MyTest2.java:20)
        try-catch成功,程序即使发生异常依然可以执行后续代码。

        Process finished with exit code 0 进程正常终止
         */
    }
}

try-catch处理多个异常

package org.westos.demo;

import java.util.Arrays;

/**
 * @author lwj
 * @date 2020/5/23 11:04
 */
public class MyTest3 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3};
        arr = null;
        try {
            System.out.println(arr[0]);
            System.out.println(10 / 0);
            System.out.println(arr[3]);
        } catch (NullPointerException e) {
            System.out.println(e);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
        } catch (Exception e) {
            //平级关系的异常前后无所谓,如果出现父子关系的异常,那么父类异常在后,子类异常在前
            System.out.println("其他异常");
        }

        System.out.println("程序可以执行到这里。");

        /*
        java.lang.NullPointerException
        程序可以执行到这里。

        Process finished with exit code 0
         */

        /*
        程序执行到14行,出现空指针异常,第一个catch分支捕获到该异常,打印该异常对象e,然后不再执行try后面的代码
         */
    }
}

JDK 1.7针对多个平级异常的处理

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/23 11:15
 */
public class MyTest4 {
    public static void main(String[] args) {
        String str = "Hello";
        String[] strs = new String[]{"Java", "JavaScript", "Python"};

        try {
            str = null;
            System.out.println(str.length());
            System.out.println(str.charAt(5));
            System.out.println(strs[3]);
        } catch (StringIndexOutOfBoundsException | ArrayIndexOutOfBoundsException | NullPointerException e) {
            e.printStackTrace();
        }
        
        /*
        java.lang.NullPointerException
	        at org.westos.demo.MyTest4.main(MyTest4.java:14)

        Process finished with exit code 0
         */
    }
}

好处:简化代码;

弊端:对多个异常的处理方式是一致的。

注意事项:

多个异常之间只能是平级的关系,不能出现子父类的继承关系。

技术图片

编译期异常和运行期异常的区别

Java中的异常分为两大类:编译时异常和运行时异常。

所有RuntimeException类及其子类的实例被称为运行时异常,其他的异常就是编译时异常。

编译时异常:Java程序必须显式处理,否则程序无法通过编译;

运行时异常:无需显式处理,也可以和编译期异常一样处理。

package org.westos.demo2;

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

/**
 * @author lwj
 * @date 2020/5/23 12:28
 */
public class MyTest {
    public static void main(String[] args) {
        //编译期异常
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = "2020-05-23 12:30:17";
        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);
        //Sat May 23 12:30:17 CST 2020
        
        /*
        public Date parse(String source) throws ParseException
        {
            ParsePosition pos = new ParsePosition(0);
            Date result = parse(source, pos);
            if (pos.index == 0)
                throw new ParseException("Unparseable date: \"" + source + "\"" ,
                    pos.errorIndex);
            return result;
        }
        throw在方法内部主动抛出一个异常,throws在方法上,是处理异常除了try-catch的另一种方式
         */
    }
}

编译期异常

  • 方法中调用的方法需要捕获异常
  • 方法中手动throw抛出编译期异常

解决:

  • try-catch
  • throws手动抛出,在方法上声明

Throwable类的常见方法

package org.westos.demo3;


import java.text.ParseException;

/**
 * @author lwj
 * @date 2020/5/23 14:40
 */
public class MyTest {
    public static void main(String[] args) {
        try {
            //try本来是存放可能会发生异常的代码
            //现在却是肯定会发生异常的代码
            throw new ParseException("aaa", 1);
        } catch (ParseException e) {
            //对于异常的处理,不要做空处理
            e.printStackTrace();
            //打印异常的详细堆栈信息(与jvm处理方式一致)
            System.out.println(e.getMessage());
            //获取异常信息,返回字符串
            System.out.println(e.toString());
            //获取异常类名和异常信息,返回字符串
        }
        System.out.println("Bye");

        /*
        java.text.ParseException: aaa
            at org.westos.demo3.MyTest.main(MyTest.java:15)
        aaa
        java.text.ParseException: aaa
        Bye
         */
    }
}

利用异常机制录入一个整数

package org.westos.demo3;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * @author lwj
 * @date 2020/5/23 14:50
 */
public class MyTest2 {
    public static void main(String[] args) {
        while (true) {
            try {
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入一个整数:");
                int num = sc.nextInt();
                System.out.println(num);
                break;
            } catch (InputMismatchException e) {
                System.out.println("输入类型不正确,请重新输入");
            }
        }
        
        /*
        请输入一个整数:
        12das
        输入类型不正确,请重新输入
        请输入一个整数:
        12
        12
        
        Process finished with exit code 0
         */
    }
}

throws的方式处理异常

package org.westos.demo3;

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

/**
 * @author lwj
 * @date 2020/5/23 14:53
 */
public class MyTest3 {
    public static void main(String[] args) throws ParseException {
        Date date = dateParseStr("2020-05-23 12:00");
        //如果发生异常,交给jvm处理
        System.out.println(date);
        //Sat May 23 00:00:00 CST 2020
    }

    private static Date dateParseStr(String s) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(s);
    }
}

throw概述和throws的区别

异常

  • 编译期异常
    • 调用throws声明的API方法
    • 自定义方法中存在throw
    • try-catch / throws向上抛出 来处理
  • 运行时异常
    • 代码逻辑存在运行时异常
    • 手动throw抛出
    • 不处理,交给jvm处理
    • 处理,try-catch处理,不要让程序停掉

throws

  • 用在方法声明后面,跟的是异常类名
  • 可以跟多个异常类名,用逗号隔开
  • 表示抛出异常,由该方法的调用者来处理
  • throws表示出现异常的一种可能性,并不一定会发生这些异常

throw

  • 用在方法体内,跟的是异常对象名
  • 只能抛出一个异常对象名
  • 这个异常对象可以是编译期异常对象,可以是运行期异常对象
  • 表示抛出异常,由方法体内的语句处理
  • throw则是抛出了异常,执行throw则一定抛出了某种异常
package org.westos.demo2;

import java.text.ParseException;

/**
 * @author lwj
 * @date 2020/5/23 13:51
 */
public class MyTest3 {
    public static void main(String[] args) throws ParseException {
        //throw new RuntimeException("");

        /*
        Exception in thread "main" java.lang.RuntimeException:
	        at org.westos.demo2.MyTest3.main(MyTest3.java:11)

        Process finished with exit code 1
         */

        /*
        手动抛出异常
        *   运行期异常:可以不处理,交给调用main的jvm处理
        *   编译期异常:必须处理,throws向上抛出
         */

        throw new ParseException("aaa", 1);

        /*
        Exception in thread "main" java.text.ParseException: aaa
	        at org.westos.demo2.MyTest3.main(MyTest3.java:26)

        Process finished with exit code 1
         */
    }
}

一般而言,工具类里的方法不要处理异常,最好抛出去让调用者处理异常逻辑。

throw抛出运行时异常

package org.westos.demo3;

/**
 * @author lwj
 * @date 2020/5/23 14:59
 */
public class MyTest4 {
    public static void main(String[] args) {
        System.out.println(10 / 0);
    }
    
    /*
    Exception in thread "main" java.lang.ArithmeticException: / by zero
        at org.westos.demo3.MyTest4.main(MyTest4.java:9)
    
    Process finished with exit code 1
     */

    public static int div(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("除数为0");
            //抛出运行时异常
        }
        return a / b;
    }
}
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

public
class IllegalArgumentException extends RuntimeException {}

如果集合的初始化容量为负数,那么抛出非法参数异常(运行时异常),如果触发了该异常,那么交给jvm处理,停止程序。

finally关键字

被finally控制的语句体一定会执行(前提 jvm没有停止)
特殊情况:在执行到finally之前jvm退出了(比如System.exit(0))

用于释放资源,在IO流操作和数据库操作中会见到。

package org.westos.demo2;

import java.util.Scanner;

/**
 * @author lwj
 * @date 2020/5/23 13:37
 */
public class MyTest2 {
    public static void main(String[] args) {
        //shift + alt + 上/下键:上下移动光标所在行代码

        Scanner sc = null;
        try {
            sc = new Scanner(System.in);
            System.out.println("请输入第一个整数:");
            int a = sc.nextInt();
            System.out.println("请输入第二个整数:");
            int b = sc.nextInt();
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println(e.toString());
        } finally {
            //无论try代码块是否有异常,finally代码块中的代码都会执行
            if (sc != null) {
                sc.close();
            }
        }
        System.out.println("Bye");

        /*
        请输入第一个整数:
        12
        请输入第二个整数:
        0
        java.lang.ArithmeticException: / by zero
        Bye
         */
    }
}

异常面试题

try-catch-finally与return的结合问题

结论:

1、不管try代码块是否有异常,finally代码块都会执行;

2、当try或者catch代码块中有return语句时,finally代码块也会执行;

3、finally是在return 后面的表达式运算后执行的,所以返回值是在finally执行前确定;

4、finally中最好不要包含return,否则程序会提前退出,返回值不是try/catch中保存的值。

举例:

1、try{} catch(){} finally{} return

程序按顺序执行

2、try{return} catch(){} finally{} return

程序执行try块中return之前的代码,包括return后面的表达式的运算,再执行finally块,最后执行try中的return。finally块之后的语句return,因为程序在try中已经return所以不再执行。

3、try{ } catch(){return;} finally{} return;

程序先执行try,如果遇到异常执行catch块,
有异常:则执行catch中return之前(包括return语句中的表达式运算)代码,再执行finally语句中全部代码,最后执行catch块中return. finally之后的代码不再执行。
无异常:执行完try再finally再return。

4、try{ return; }catch(){} finally{return;}

程序执行try块中return之前(包括return语句中的表达式运算)代码;再执行finally块,因为finally块中有return所以提前退出。

5、try{} catch(){return;}finally{return;}

程序执行catch块中return之前(包括return语句中的表达式运算)代码;再执行finally块,因为finally块中有return所以提前退出。

6、try{ return;}catch(){return;} finally{return;}

程序执行try块中return之前(包括return语句中的表达式运算)代码;
有异常:执行catch块中return之前(包括return语句中的表达式运算)代码;再执行finally块,因为finally块中有return所以提前退出。
无异常:则再执行finally块,因为finally块中有return所以提前退出。

自定义异常

Java提供的异常不能完成业务逻辑。

继承自Exception:编译时异常

继承自RuntimeException:运行时异常。

package org.westos.demo4;


/**
 * @author lwj
 * @date 2020/5/23 15:13
 */
public class MyException extends RuntimeException {
    public MyException(String s) {
        super(s);
    }
}
package org.westos.demo4;

import java.util.Scanner;

/**
 * @author lwj
 * @date 2020/5/23 15:13
 */
public class MyTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的成绩:");
        int score = sc.nextInt();
        if (score > 100 || score < 0) {
            throw new MyException("成绩无效");
        }
        System.out.println(score);

        /*
        请输入你的成绩:
        101
        Exception in thread "main" org.westos.demo4.MyException: 成绩无效
            at org.westos.demo4.MyTest.main(MyTest.java:15)

        Process finished with exit code 1
         */
    }
}

异常的注意事项

(针对编译期异常)

在方法重写中,子类方法抛出的异常不能大于父类方法抛出的异常。

  • 如果父类被重写的方法没有异常抛出,那么子类的方法绝对不能抛出异常,如果子类方法有异常发生,那么只可以try-catch,不可以throws。

  • 子类方法的访问级别不能小于父类方法的访问级别

  • 子类方法的返回值类型不能大于父类方法的返回值类型

  • 子类方法抛出的异常不能大于父类方法抛出的异常

File类

File类的构造方法

File(String pathname) 
File(String parent, String child) 
File(File parent, String child) 
package org.westos.demo;

import java.io.File;

/**
 * @author lwj
 * @date 2020/5/23 16:08
 */
public class MyTest {
    public static void main(String[] args) {
        File file = new File("E:\\XiBuKaiYuan\\JavaSEDirectory\\0523\\day19.md");
        System.out.println(file);
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\day19.md

        File file1 = new File("E:\\XiBuKaiYuan\\JavaSEDirectory\\0523", "day19.md");
        System.out.println(file1);
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\day19.md

        File file2 = new File("E:\\XiBuKaiYuan\\JavaSEDirectory\\0523");
        //目录对象
        File file3 = new File(file2, "day19.md");
        System.out.println(file3);
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\day19.md

        System.out.println(File.separator);
        //        System.out.println(File.pathSeparator);
        //; 与系统有关的路径分割符
    }
}

相对路径与绝对路径

package org.westos.demo;

import java.io.File;

/**
 * @author lwj
 * @date 2020/5/23 16:27
 */
public class MyTest2 {
    public static void main(String[] args) {
        /*
        绝对路径:带有盘符的详细路径
        相对路径:不带盘符的路径,在Java程序中相对于当前项目下
         */
        File file = new File("src\\org\\westos\\demo\\MyTest.java");
        System.out.println(file);
        //src\org\westos\demo\MyTest.java
        System.out.println(file.getAbsolutePath());
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\File类\src\org\westos\demo\MyTest.java
        System.out.println(new File(".").getAbsolutePath());
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\File类\.
        //.代表当前目录
        System.out.println(new File("..").getAbsolutePath());
        //E:\XiBuKaiYuan\JavaSEDirectory\0523\File类\..
        //点击上面的路径可以调到本地文件系统的0523目录下
    }
}

技术图片

File类的创建

方法名 描述
public boolean createNewFile() 当且仅当具有该名称的文件尚不存在时,创建一个路径名命名的新的空文件。
public boolean mkdir() 创建由此抽象路径名命名的目录
public boolean mkdirs() 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。
package org.westos.demo;

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

/**
 * @author lwj
 * @date 2020/5/23 16:41
 */
public class MyTest3 {
    public static void main(String[] args) {
        File file = new File("src\\org\\westos\\demo\\a.txt");
        try {
            boolean newFile = file.createNewFile();
            System.out.println(newFile);
            //是否创建成功
            //当第一次创建时返回true,如果已经存在,重复创建,返回false
        } catch (IOException e) {
            e.printStackTrace();
        }

        File file1 = new File("src\\org\\westos\\demo2");
        boolean mkdir = file1.mkdir();
        System.out.println(mkdir);
        //是否创建成功
        //当第一次创建时返回true,如果已经存在,重复创建,返回false

        File file2 = new File(".\\src\\org\\test\\demo");
        boolean mkdirs = file2.mkdirs();
        System.out.println(mkdirs);
        //是否创建成功
        //当第一次创建时返回true,如果已经存在,重复创建,返回false
    }
}

File类的删除

方法名 描述
public boolean delete() 删除由此抽象路径名表示的文件或目录
package org.westos.demo;

import java.io.File;

/**
 * @author lwj
 * @date 2020/5/23 16:54
 */
public class MyTest4 {
    public static void main(String[] args) {
        //删除文件
        File file = new File("src\\org\\westos\\demo\\a.txt");
        boolean delete = file.delete();
        System.out.println(delete);
        //true

        //注意事项:Java中的删除不走回收站。要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹
        File file1 = new File("src\\org\\test");
        boolean delete1 = file1.delete();
        System.out.println(delete1);
        //false
        //test文件夹下含有demo文件夹

        File file2 = new File("src\\org\\test\\demo");
        boolean delete2 = file2.delete();
        System.out.println(delete2);
        //true
        //demo文件夹已被删除,test文件夹没有子文件夹

        boolean delete3 = file1.delete();
        System.out.println(delete3);
        //true
    }
}

23、异常、File类(构造方法、创建、删除)

标签:遇到   容量   inter   return语句   ann   jvm   data   mat   特殊   

原文地址:https://www.cnblogs.com/shawnyue-08/p/12943566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!