2019-05-29 Java学习日记 day19

异常

异常就是就AV按程序在运行过程中出现的错误

异常分类:

  通过API查看Throwable

  Error

    服务器启机,数据库崩溃等

  Exception

异常的继承体系

  Throwble

    Error

    Exception

      RuntimeException

JVMmore是如何处理异常的

  main函数收到这个问题时,有两种处理方式

  *自己将该问题处理,然后继续运行

  *自己没有针对的处理方式,只有交给调用main的jvm来处理

  jvm有一个默认的异常处理机制,就将该异常进行处理

  并将该异常的名称,异常出现的位置打印在了控制台上,同事将程序停止运行

异常处理的两种方式

  try...catch...finally

    *try catch

    *try catch finally

    *try finally

  try...catch处理异常的基本路线

    *try...catch...finally

public class demo2_Exception {
    /*    try:用来检测异常
     *     catch:用来捕获异常
     *     finally:释放资源
     * */
    public static void main(String[] args) {
        demo d=new demo();
        
        try{
        int x=d.div(10, 0);
        System.out.println(x);        
        }
        
        catch(ArithmeticException a){
        //ArithmeticException a =new ArithmeticException()
            
            System.out.println("出错了");
        }
        
    }

}
 class demo{
     public int div(int a,int b){
            return a/b;
        }
 }
try...catch处理异常_1
public class demo3_Exception {
    /*try后面如果跟多个catch,那么小的异常放前面,大的异常放后面,根据多态的原理
     *     如果大的放前面,就会将所有的子类对象接受,后面的catch既没有意义了
     * */
    public static void main(String[] args) {
        int a=10;
        int b=0;
        int [] arr={11,22,33,44,55};
        //JDK如果处理多个异常            
        try {
            System.out.println(a/b);
            System.out.println(arr[10]);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println("出错了");
        } /*catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("索引越界了");
        } catch (Exception e) {
            System.out.println("有误");
        }*/
        
    }

}
try...catch处理多个异常

编译期异常和运行期异常

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

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

  

  编译时异常:

    java程序必须显示处理,否则程序就会发生错误,无法通过编译

  运行时异常:

    无需显示处理,也可以和编译时异常一样处理

Throwable的几个常见方法

  *getMessage()

    *获取异常信息,返回字符串

  *toString()

    *获取异常类名和异常信息,返回字符串

  *printStackTrace()

    *获取异常类名的异常信息,以及异常出现在程序中的位置,返回void

public class demo5_Throwable {

    public static void main(String[] args) {
        try {
            System.out.println(10/0);
        } catch (Exception e) {  //Exception e =new Arithmeticexception("/by aero")
            //System.out.println(e.getMessage());  //获取异常信息
            //System.out.println(e.toString());   //获取异常类名
            //System.out.println(e);  //调用toString方法,打印异常类名和异常信息
            e.printStackTrace();  //jvm默认就用这种方式处理异常
        }
    }

}
三种方法

throw的方式处理异常

 *定义功能方式是,需要把出现的问题暴露出来让调用者去处理

 *那么久通过throw在方法上标识

编译时异常的抛出必须对其进行处理

运行时异常的抛出可以处理也可以不处理

public class demo6_Exception {

    public static void main(String[] args)throws Exception  {
        Person p1= new Person();
        p1.setAge(-17);
        System.out.println(p1.getAge());
    }

}
class Person{
    private String name;
    private int age;
    public Person() {
        super();
        
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) throws Exception  {     // RuntimeException运行时异常
        if(age >0 && age <=150){       //Exception 编译时异常
            this.age = age;
        }else {
            throw new Exception("年龄非法");
        }
        
    }
    
}
案例

throw的概述和throws的区别

throw概述:

  *在功能方法内部出现某种情况,程序不能进行运行,需要进行跳转时,就用throw把异常对象抛出

throw和throws区别:

  throw:

    *用在方法声明后面。跟的是异常类名

    *可以跟多个异常类名,用逗号隔开

    *表示抛出异常,由该方法的调用者来处理

  throws:

    *用在方法体内,跟的是异常对象名

    *只能抛出一个异常对象名

    *表示抛出异常,由方法体内的语句处理

finally关键字

  finally的特点

    被finally控制的语句体一定会执行

    特殊情况:在执行到finally之前jvm退出了(比如System.exit(0))

  finally的作用

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

public class demo7Finally {

    public static void main(String[] args) {
        try {
            System.out.println(10/0);
        } catch (Exception e) {
            System.out.println("出错了");
            System.exit(0);   //退出jvm虚拟机
            return ;  //相当于方法的最后一口气,在最后会看一看finally有没有完成方法,如果有就将finally执行
        }finally {
            System.out.println("我执行了吗");
        }

    }

}
案例

final,finally,finalize的区别

public class test1 {
    /*    final:可以修饰类,不能被继承
     *           修饰方法,不能被重写
     *          修饰变脸,只能赋值一次
     *     
     *     finally是try语句中的语句体,你能单独使用,用来释放资源
     * 
     *     finalize是一个方法,当来及回收器确定不存在对象的跟多引用时,由对象的垃圾回收器调用此方法
     * */
    public static void main(String[] args) {
        demo d1=new demo();
        System.out.println(d1.method());

    }

}
class demo{
    public  int method(){
        int x=10;
        try {
            x=20;    
            System.out.println(1/0);
            return x;
        } catch (Exception e) {
            x=30;                
            return x;//建立返回路径
        }finally{
            //System.out.println("1");
            x=40;
            //return x;  不要在finally里面写返回语句,因为finally的作用是为了释放资源,是肯会执行的
                        //如果在这里面写返回语句,那么try和catch的结果都会被改变,所以这么写就是不行
        }
    } 
    
}

自定义异常

public class demo8_Exception {

    public static void main(String[] args) {
        

    }

}
//Ait + Shift + S -C   构造重写
class AgeOutOfBoundsException extends RuntimeException{

    public AgeOutOfBoundsException() {
        super();
        
    }

    public AgeOutOfBoundsException(String message) {
        super(message);
        
    }
    
}
案例

try嵌套

public class test3 {

    
    
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        System.out.println("请输入一个整数");
        
        while (true) {    
        String line =scanner.nextLine();
        try{
            
        int num = Integer.parseInt(line);   //将字符串转换为整数
        System.out.println(Integer.toBinaryString(num));//将整数转换为二进制
        break;  //跳出循环
        }catch(Exception e){
            try{
            new BigInteger(line);  //过大整数
            System.out.println("录入错误,请重新录入");    
            }catch(Exception e1){
                
                try{
             new BigDecimal(line);
             System.out.println("录入的是小数,请重新录整数");    
                }catch(Exception e2){
                    System.out.println("录入的是非法字符,请重新录入");
                }
            }
            
        }
    }
}

}
//alt +shift+z (try...catch)
练习题

File类

  File更应该叫做一个路径

    *文件路径或者文件夹路径

    *路径分为绝对路径和相对路径

    *绝对路径是一个固定的路径,从盘符开始

    *相对路径相对于某个位置,在eclipse下是治党前项目下,在dos下指的是当前路径

  构造方法

    *File(String pathname):根据一个路径得到File对象

    *File(String paerent,String child):根据一个目录和一个子文件/目录得到File对象

    *File(File paernt,String child):根据一个父File对象和一个子文件/目录得到File对象

import java.io.File;

public class demo1_File {

    public static void main(String[] args) {
        //demo1();
        //demo2();
        File parent= new File("D:\java");
        String child="demo1_nonameinnerclass.java";
        File file =new File(parent,child);
        System.out.println(file.exists());

    }

    public static void demo2() {
        String parent="D:\java";
        String child="demo1_nonameinnerclass.java";
        File file =new File(parent,child);
        System.out.println(file.exists());
    }

    public static void demo1() {
        File file= new File("D:\java\demo1_nonameinnerclass.java");
        System.out.println(file.exists());
    }

}
案例

File添加功能

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

public class demo2_FileMethod {
    /* 创建功能
     *         public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了
     *         public boolean mkdir():创建文件夹 如果存在这样的文件夹 就不创建了
     *         public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来
     * */
    public static void main(String[] args) throws IOException {
        //demo1();
        File file =new File("aaa");
        System.out.println(file.mkdir());
        
        File file2 =new File("ttt.txt");
        System.out.println(file2.mkdir());
        
        File file3 =new File("ccc\ttt");
        System.out.println(file3.mkdirs());  //多级目录
        
    }

    public static void demo1() throws IOException {
        File file =new File("jung.txt");
        try {
            System.out.println(file.createNewFile());  //如果没有就创建,返回true
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file2 =new File("jun");
        System.out.println(file2.createNewFile());
    }

}

File重命名和删除功能

   public boolaean rename(File dest):把问价重命名为指定的文件路径

   public boolean delete():删除文件或者文件夹

重命名注意事项

  如果路径名相同,就是改名

  如果路径名不同,就是改名并剪切

删除注意事项

  java中的删除不走回收站

  要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹

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

public class demo3_File {

    public static void main(String[] args) throws IOException {
        //demo1();
        File file1=new File("aaa");
        System.out.println(file1.delete());

    }

    public static void demo1() {
        File file1=new File("xxx.txt");
        File file2=new File("aaa.txt");
        System.out.println(file1.renameTo(file2));
    }

}
案例

File判断功能

  *public boolean isDirectory():判断是否是目录

  *publicboolean isFile():判断是否是文件

  *public boolean exists():判断试试存在

  *public boolean canRead():判断是否可写

  *public boolean isHidden():判断是否隐藏

File判断指定目录下的文件是否存在后缀名

import java.io.File;

public class test4 {

    public static void main(String[] args) {
        //demo1();
        File dir= new File("D:\");
        File[] subFiles =dir.listFiles(); //获取d盘下所有文件夹或文件夹对象
        for (File file : subFiles) {
            if(file.isFile() && file.getName().endsWith(".txt")){
                System.out.println(file);
            }
        }

    }

    public static void demo1() {
        File dir= new File("D:\");
        String [] arr =dir.list(); //获取d盘下所有的文件或文件夹
        for (String string : arr) {
            if(string.endsWith(".txt")){
                System.out.println(string);
            }
        }
    }

}
案例

File过滤器

  public String [ ] list(FilenameFilter filter)

  public File [ ]  listFiles(FileFilter filter)

文件夹名称过滤器的使用

  需求:判断D盘努力下是否有后缀名为 .txt 的文件,如果头。就输出该文件名称

原码分析

  带文件名称过滤器的list()方法的源码

public static void main(String[] args) {
        //demo1();
        //demo2();
        File dir= new File("D:\");
        String [] arr=dir.list(new FilenameFilter() {
            
            public boolean accept(File dir, String name) {
                //System.out.println(dir);
                //System.out.println(name);
                File file =new File(dir,name);
                
                return file.isFile() && file.getName().endsWith(".txt");
            }
        });
        for (String string : arr) {
            System.out.println(string);
        }

    }
}
案例
原文地址:https://www.cnblogs.com/JungTan0113/p/10947240.html