day17达内

来源:互联网 发布:网络做印刷怎么找客户 编辑:程序博客网 时间:2024/04/30 20:02

今天讲的自定义异常关键词有:throws,throw以及try catch语句

throws可以形容成抛异常的管道;其中每个管道自能抛出自己类型的异常但是RuntimeException默认存在的
所以RuntimeException及其子类型异常都可以从默认管道抛出,其他所有异常都需要二选一(1)throws添加管道(2)try-catch捕获。而throw关键字的意思是手动抛出一个异常,我们也可以将捕获的异常对象包装在其他的异常对象中,再抛出,下面是几个实例:

package tarena.day1701;import java.io.File;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;public class Test1 {    public static void main(String[] args) {        try {            f();        } catch (ParseException e) {            System.out.println("格式错误");            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            System.out.println("无法创建文件");            // TODO Auto-generated catch block            e.printStackTrace();        }    }    public static void f() throws ParseException, IOException {        System.err.println("输入生日(yyyy-MM-dd)");        String s = new Scanner(System.in).nextLine();        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");        Date d = fmt.parse(s);        long t = d.getTime();        File f = new File("d:/"+t+".txt");        f.createNewFile();    }}
package tarena.day1701;import java.util.Scanner;public class Test2 {    public static void main(String[] args) {        System.out.println("输入两个浮点数");        double a =new Scanner(System.in).nextDouble();        double b= new Scanner(System.in).nextDouble();        try {            double c= divide(a,b);            System.out.println(c);        } catch (ArithmeticException e) {            System.out.println("别怪我");            System.out.println(e.getMessage());            e.printStackTrace();        }    }    private static double divide(double a, double b) {        if(b==0){            ArithmeticException e=new ArithmeticException("/by zero");            throw e;        }        return a/b;    }}
package tarena.day1701;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Comparator;import java.util.Date;import java.util.List;import java.util.Collections;public class Test3 {    public static void main(String[] args) {        List<String> list = new ArrayList<>();        Collections.addAll(list,"2016-10-12","2011-58-52","2014-10-1","2015-1-5");        System.out.println(list);        //main()-->sort()-->compare()        Collections.sort(list,new Comparator<String>() {            public int compare(String o1,                    String o2) {            SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd");            try {                Date d1 =f.parse(o1);                Date d2 = f.parse(o2);                return d1.compareTo(d2);            } catch (ParseException e) {                RuntimeException re=new RuntimeException(e);                throw re ;            }            }        });        System.out.println(list);    }}
0 0
原创粉丝点击