java(异常)

目录

一.匿名对象

二.Lambda 表达式

三.异常

四.异常处理方案

五.自定义异常

六.常用类

七.String类中的方法


一.匿名对象

匿名对象: 是对象,没有引用指向这个对象 匿名内部类 : 没有名字的一个内部类 作用: 简化没有类本身作用,只为了重写的一些抽象方法,方便调用这个方法 ,匿名内部类就可以简化这种实现类 简化符合需求的实现类,子类->接口|抽象父类

package com.xxxx.shuZu;
​
public class Class005_NiMing {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.smoking();
        new Smoke() {  //匿名内部类的类体
            @Override
            public void smoking() {
                System.out.println("我想要甘雨");
            }
        }.smoking();
​
​
        Smoke s = new Smoke() {
            @Override
            public void smoking() {
                System.out.println("我想要莫娜");
            }
        };
        s.smoking();
        s.smoking();
        s.smoking();
        s.smoking();
​
        test(new Kevin());
        test(new Demo());
        test(new Smoke() {
            @Override
            public void smoking() {
                System.out.println("我想要可莉");
            }
        });
​
    }
​
    static void test(Smoke smoke){
        smoke.smoking();
    }
​
}
​
interface Smoke{
    void smoking();
}
​
class Kevin implements Smoke{
    public String name;
    int age;
​
    @Override
    public void smoking() {
               System.out.println("我想要一个刻晴");
​
    }
//    @Override
//    public void smoking(){
//        System.out.println("我想要一个刻晴");
//    }
}
class Demo implements Smoke{
    public void smoking(){
        System.out.println("我想要一个莎拉");
    }
}

二.Lambda 表达式

Lambda 表达式 -> jdk8新增 作用: 就是为了简化匿名内部类结构

前提: 函数式接口

函数式接口 : 只存在一个必须被重写的抽象方法的接口 ​ 检查一个接口是否为函数式接口: @FunctionalInterface

结构: ​ ()->{} ​ () : 重写的抽象方法的参数列表 ​ {} : 重写抽象方法的方法体 ​ -> : lambda符号,箭头符号,具有上下文推导的作用

​
​
public class Class001_Lambad {
    public static void main(String[] args) {
        Swim s=null;
​
​
//        Swim s=new Swim() {
//            @Override
//            public void Swim() {
//                System.out.println("我韩跳跳贼六");
//            }
//        };
//        s=()->{
//            System.out.println("边路霸主");
//        };
//        s=()-> System.out.println("请求对抗路支援");
//
//    }
   //s=i ->System.out.println("请求对抗路支援");
    //    s=(int i,int j)-> System.out.println("皆是牛马");
​
        //s = (a,b) ->{return a+b;};
        s = (a,b) ->a+b;
​
        s.swim(1,2);
}
}
@FunctionalInterface
interface Swim{
    int swim(int i,int j);
​
}

三.异常

异常 程序出现了问题 程序一旦遇到异常,后面代码无法正常执行,并且同时控制台中展示异常的详细信息|细节问题,便于程序猿的调试

异常体系: Throwable / \ Error Exception

Error : 一般指由虚拟机生成并脱出的,无需程序猿解决处理 Exception : 异常 异常如果不处理,程序无法正常执行,需要程序猿在代码层面上处理异常 RuntimeException 运行时异常 : 运行期间才会发生的异常 CheckedException 编译时异常|检查时异常 : 编译期间发生的异常,不处理程序无法运行

重点学习关注异常处理方案: 所有的异常都可以通过标准异常处理方案来处理 运行时异常一般通过增强程序健壮性的代码就可以解决 -> if判断 编译时异常只能通过异常处理方案来处理

思考: 列举几个常见的运行异常 NullPointerException 空指针异常 ArithmeticException 数学异常 ArrayIndexOutOfBoundsException 数组索引越界异常 NegativeArraySizeException 数组长度负数异常 ClassCastException 类型转换异常 NumberFormatException 转换格式异常

public class Class001_Exception {
    public static void main(String[] args) {
        //NullPointerException 空指针异常
        String s = "abc";
        s = null;
        //判断  增强程序 健壮性的代码
        if(s!=null){
            System.out.println(s.length());
        }else{
            s = "";
        }
​
        System.out.println("main方法结束");
​
        //ArithmeticException 数学异常
        //System.out.println(5/0);
​
        //ArrayIndexOutOfBoundsException 数组索引越界异常
        //NegativeArraySizeException 数组长度负数异常
        //int[] arr = new  int[-3];
        //System.out.println(arr[3]);
​
        //ClassCastException 类型转换异常
        //Object obj = "张三";
        //System.out.println((Class001_Exception)obj);
​
        //NumberFormatException 转换格式异常
        String str = "123abc";
        System.out.println(Integer.valueOf(str));
​
        //编译时期异常
        //InputStream is = new FileInputStream("");
​
    }
}

四.异常处理方案

异常处理方案: 1.异常抛出 throws 把异常抛出到上一层,谁调用谁处理 2.异常捕获 异常对象当前抓住捕获,直接处理

try { ​ 可能会出现异常的代码; ​ } catch (FileNotFoundException e) { ​ e.printStackTrace(); ​ } catch (NullPointerException e) { ​ e.printStackTrace(); ​ } catch (Exception e) { --> 接盘侠 ​ System.out.println("出现了文件未找到异常, 捕获异常..."); ​ e.printStackTrace(); ​ }

注意: ​ 1.异常一旦处理,不影响程序的继续执行 ​ 2.try中代码可能出现异常,可能不会出现异常, ​ 如果没有出现异常,try{}中的代码执行完毕,try...catch结束 ​ try中代码一旦异常,try后面的代码不会执行,直接执行catch的判断 ​ 从上到下一次判断,判断当前的catch是否能够捕获出现的异常对象,如果能,执行后面的{}中的代码, ​ 如果不能匹配,继续向下判断,如果所有的都不鞥匹配,当前的异常对象没有处理,中止程序的执行

3.一个try后面可以跟1~n个catch ​ 4.如果一个异常已经通过catch处理不影响后面代码的执行 ​ 5.接收范围较大的异常的catch,需要定义在后面 ​ 6.finally 最终的 ​ 无论try中是否会出现异常,finally中的代码肯定最后会执行 ​ 一般会定义一些资源的关闭等代码

public class Class002_Exception {
    public static void main(String[] args){
        //编译时期异常
        //InputStream is = new FileInputStream("");
​
        try {
            System.out.println("try开始了....");
            test();
            System.out.println(5/0);
            System.out.println("try结束了....");
        } catch (FileNotFoundException e) {
            System.out.println("出现了文件未找到异常, 捕获异常...");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("接盘侠");
            e.printStackTrace();
        } finally {
            System.out.println("最后肯定会执行的代码");
        }

五.自定义异常

自定义异常 异常类也是类 需要直接或者间接的继承自Exception 如果是运行时期异常必须直接或者间接的继承RuntimeException

制造异常: throw

package com.xxxx.Ke;
​
public class Class003_Exception {
    public static void main(String[] args) {
    User user=new User();
    user.setName("lisi");
    int age=19;
        try {
            user.setAge(30);
        } catch (Exception e) {
            e.printStackTrace();
        }
​
        System.out.println("吉吉国王");
}
}
​
class AgeException extends Exception{
    public AgeException() {
    }
​
    public AgeException(String message) {
        super(message);
    }
​
}
class User{
    private String name;
    private int age;
​
    public User() {
    }
​
    public User(String name) {
        this.name = name;
​
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public int getAge(int i) {
        return age;
    }
​
    public void setAge (int age) throws Exception{
        if(age<18||age>100){
            throw new AgeException("年纪不合法");
        }
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                '}';
    }
}

六.常用类

常用类 : 经常使用的类

字符串String 不可变长字符序列 String类表示字符串。 Java程序中的所有字符串文字(例如"abc" )都实现为此类的实例。 "abc" 字符串常量 --> 字符串常量池中-> 方法区 new String() --> 堆中

学习API类型: 了解类的作用与特点 学习构造器 学习方法 成员 非静态 静态的

底层分析: ​ jdk11 ->使用字节数组存储字符串数据 private final byte[] value; ​ jdk8 -> 使用字符数组存储字符串数据 private final char[] value;

package com.xxxx.Ke;
import java.io.UnsupportedEncodingException;
public class Class004_Exception {
​
​
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str="";
        str="abc";
        String srt1=new String();
​
        String str2 = new String();
        System.out.println(str2);
​
        String str3 = new String("haha");
        System.out.println(str3);
​
        char[] ch = {'c','y','d','z','m'};
        String str4 = new String(ch);
        System.out.println(str4);
​
        String str5 = new String(ch,1,3);
        System.out.println(str5);
​
        byte[] arr = "中国".getBytes("GBK");
        System.out.println(arr.length);
​
        String str6 = new String(arr,"GBK");
        System.out.println(str6);
​
        String str8 = new String(arr,2,2,"GBK");
        System.out.println(str8);
​
​
    }
}
​

七.String类中的方法

public class Class002_StringMethod {
    public static void main(String[] args) {
        String str = "jintiantianqizhenhaohahaha";
        String str2 = "Jintiantianqizhenhaohahaha";
        //char charAt(int index) 返回指定索引处的 char值。
        System.out.println(str.charAt(4));
        //int codePointAt(int index) 返回指定索引处的字符(Unicode代码点)。
        System.out.println(str.codePointAt(4));
​
        //int compareTo(String anotherString) 按字典顺序比较两个字符串。
        //返回值结果 : >0 this对象大于参数anotherString   =0相等   <0 this<anotherString
        System.out.println(str.compareTo(str2));
​
        //int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,忽略大小写差异。
        System.out.println(str.compareToIgnoreCase(str2));
​
        //String concat(String str) 将指定的字符串连接到此字符串的末尾。
        System.out.println(str.concat(str2));
​
        //boolean contains(CharSequence s) 当且仅当此字符串包含指定的char值序列时,才返回true。
        System.out.println(str.contains("tian"));
​
        //boolean equals(Object anObject) 将此字符串与指定的对象进行比较。
        System.out.println(str.equals(str2));
        //boolean equalsIgnoreCase(String anotherString) 将此 String与另一个 String比较,忽略了大小写。
        System.out.println(str.equalsIgnoreCase(str2));
​
        //boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结尾。
        System.out.println(str.endsWith("haha"));
​
        //static String copyValueOf(char[] data) 相当于 valueOf(char[]) 。
        String str3 = String.copyValueOf(new char[]{'a','b','c'});
        System.out.println(str3);
​
        //byte[] getBytes() 使用平台的默认字符集将此 String编码为字节序列,将结果存储到新的字节数组中。
        //byte[] getBytes(String charsetName) 使用命名的字符集将此 String编码为字节序列,将结果存储到新的字节数组中。
        System.out.println(Arrays.toString("你好".getBytes()));
​
        //void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将此字符串中的字符复制到目标字符数组中。
        char[] ch = new char[10];
        System.out.println(Arrays.toString(ch));
        str.getChars(3,11,ch,1);
        System.out.println(Arrays.toString(ch));
​
        //int indexOf(String str) 返回指定子字符串第一次出现的字符串中的索引。
        System.out.println(str.indexOf("tian"));
        //int indexOf(String str, int fromIndex) 从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。
        System.out.println(str.indexOf("tian",5));
​
        System.out.println(str);
​
        //int lastIndexOf(int ch) 返回指定字符最后一次出现的字符串中的索引。
        //int lastIndexOf(int ch, int fromIndex) 返回指定字符最后一次出现的字符串中的索引,从指定的索引开始向后搜索。
        System.out.println(str.lastIndexOf("tian"));
        System.out.println(str.lastIndexOf("tian",5));
​
    }
}
​
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值