Java学习路程之Hashtable和异常处理

一.Hashtable
1.集合
ArrayList 查询快,增删慢
LinkedList 查询慢,增删快
HashSet 去重(重写Hashcode和Equals方法)
TreeSet 排序(实现Comparator或Comparable接口)
LinkedHashSet 去重,有存取顺序

双列集合Map 线程不安全
HashMap 去重
TreeMap 排序
LinkedHashMap 去重

线程安全 JDK1.0
Vector 被ArrayList替代
Hashtable 被HashMap替代
2.Hashtable和HashMap的区别
1).Hashtable:不可以保存null值,线程安全
2).HashMap:可以保存null值,线程不安全

public class Day17 {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        //HashMap可以保存null值
        hashMap.put("张三", null);
        hashMap.put(null, 15);
        System.out.println(hashMap);//{null=15, 张三=null}
        //Hashtable不可以保存null值
        Hashtable<String, Integer> hashtable = new Hashtable<>();
        hashtable.put("张三", null);
        hashtable.put(null, 15);
        System.out.println(hashtable);//报错NullPointerExce
    }
}

二.异常处理
1.异常类继承关系
Throwable(所有异常的父类)
子类
error
Exception 异常类 -> 子类 RuntimeException(运行时异常)
2.异常的处理方式
1).自己处理
2).交给自己的上级处理(谁调用该方法谁就是上级)
默认处理方式(JVM处理)
1).打印错误信息
2).打印异常类
3).打印错误发生的位置
4).停止程序
3.常见的异常
NullPointerException 空指针异常
IndexOutOfBoundsException 越界异常
ArithmeticException 算术异常
4.异常的处理方式
使用try…catch..finally
try 存放可能发生异常的代码
catch 匹配异常类的对象
finally 异常匹配完毕后肯定会执行的代码
5.使用try..catch处理异常的特点
1).程序不会停止
2).catch匹配成功后执行括号中的语句
3)执行括号中的语句后程序继续执行
6.try..catch处理异常的流程
1).发生异常时,系统创建一个异常对象,并携带异常信息返回出去
2).调用异常方法会接收返回的异常对象,发生异常后的代码不再执行
3).catch匹配异常对象,匹配成功后执行catch中的代码
4).继续执行下面的代码

public class Day17 {
    public static void main(String[] args) {
        try{
            int a = 2;
            double num = 10/a;
            //发生异常后之后的代码不再执行
            System.out.println(num);//不执行
        }catch(ArithmeticException e){
            //异常对象匹配成功后执行下面的代码
            System.out.println("我是catch里面的代码");//我是catch里面的代码
        }
        System.out.println("程序继续运行");//程序继续运行
    }
}

7.try…catch..finally中的finally
特点:无论是否发生异常,finally中的语句一定会被执行
作用:用于关闭数据库;关闭流资源
8.final finally finalize
他们之间没有关系
final 修饰类(不能继承),修饰方法(不能重写),修饰变量(不可修改)
finally 异常处理时使用多用于关闭资源
finalize 方法名在Object类中,当对象成为垃圾系统自动调用该方法,将对象销毁

public class Day17 {
    public static void main(String[] args) {
        try {
            int num = 10 / 0;
            System.out.println(num);//不执行
        } catch (Exception e) {
            System.out.println("你除0了");//你除0了
        }finally {
             //finally中无论是否有异常都会执行
            System.out.println("都会执行");//都会执行
        }
    }
}

9.throw和throws的区别
写法:
throw: 后面跟的是抛出异常的对象
throws:跟的是异常类的类名
位置:
throw:方法中
throws:方法上
作用:
throw:抛出一个异常对象
throws:标识方法携带一个异常
练习1
需求:
创建一个人类 有name 和 age,要求 人类的年龄赋值时 要在 0 到 120岁之间

public class Day17 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("李四");
        //自己处理异常
        try {
            person.setAge(500);
        } catch (Exception e) {
            //打印错误信息,位置
            e.printStackTrace();
        }
    }
}

人类
public class Person {
    private String name;
    private int age;
    public int getAge() {
        return age;
    }
    //控制人的年龄范围
    //抛出异常的方法需要在方法上标识一下,可能接收到异常对象. 关键词 throws  标识方法有异常
    public void setAge(int age) throws Exception{
        if (age > 0 && age < 120) {
            this.age = age;
        }else {
            //创建自定义异常类对象
            AgeOutOfBoundsException e = new AgeOutOfBoundsException("Age exceeds the scope:" + age );
            throw e;
        }
    }
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}
//自定义异常类
//年龄超出了范围
class AgeOutOfBoundsException extends Exception{
    //需要提供构造方法
    public AgeOutOfBoundsException() {
        super();
    }
    public AgeOutOfBoundsException(String message) {
        super(message);
    }
}

练习2
需求:写一个类
1.抛出运行时异常的方法
2.抛出编译时异常的方法
3.计算圆面积的方法

public class Day17 {
    public static void main(String[] args) {
        test.fn1();//编译时异常
        test.fn2();//运行时异常
        int area = test.circle(-1);
        System.out.println(area);//半径不能小于0
    }
}

class ExceptionTest {
    //抛出编译时异常
    public void fn1()throws Exception{
        throw new Exception("编译时异常");
    }
    //抛出运行时异常
    public void fn2() throws Exception{
        new RuntimeException("运行时异常");
    }
    public double circleArea(int r){
        if(r <= 0){
            throw new RuntimeException("半径不能小于0");
        }else{
            double area = 3.14 * r * r;
            return area;
        }
    }
}

练习3
无限输入整数 存放到集合中 打印 输入quit停止, 希望在输入字符串的时候 让程序也能继续运行

public class Day17 {
    public static void main(String[] args) {
        public static void main(String[] args) {
        System.out.println("请输入整数,输入quit停止");
        ArrayList<Integer> arrayList = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String nextLine = scanner.nextLine();

            if (nextLine.equals("quit")) {
                //输入quit停止循环输入
                break;
            }else { 
                //添加整数到集合
                try {
                    //字符串转整数
                    //可能出现异常
                    int num = Integer.parseInt(nextLine);
                    arrayList.add(num);
                } catch (Exception e) {
                    System.out.println("输入错误,请重新输入");
                }
            }
        }
        System.out.println(arrayList);
    }
    }
}

10.继承中的异常

class Animal{
    ///父类方法中抛出一个编译异常
    public void fn() throws Exception{}
}
class Cat extends Animal{
    //重写父类的抛出异常方法
    //子类重写父类带有异常的方法,可以选择不抛出异常
    //父类方法没有抛出异常时,子类重写方法不能抛出异常,只能选择自己处理异常
    public void fn() throws Exception{
        test();
    }
    //带异常的方法
    public void test() throws Exception{

    }
}

猜你喜欢

转载自blog.csdn.net/l710820742/article/details/82632145
今日推荐