javase(2023/11/19)

本文详细介绍了Java中的异常处理机制,包括Error和Exception的区别,运行时异常和编译时异常,try-catch-finally和throws的用法,自定义异常,以及包装类(如Integer和Character)的使用。还探讨了valueOf方法的工作原理。

1、异常

基本介绍

Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)


执行过程中所发生的异常事件可分为两大类

  • Error(错误):Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError[栈溢出]和OOM(out ofmemory). Error是严重错误,程序会崩溃。
  • Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如空指针访问,试图读取不存在的文件,网络连接中断等等,Exception 分为两大类:运行时异常[程序运行时,发生的异常]和编译时异常[编程时,编译器检查出的异常]。
     

 异常体系图

 常见运行时异常(可以暂不处理)

NullPointerException 空指针异常(null或其他)

ArithmeticException 数学运算异常(/0或其他)

ArrayIndexOutOfBoundsException 数组下标越界异常

ClassCastException 类型转换异常 (下转型或其他)

NumberFormatException 数字格式不正确异常[] (“hello”转int或其他)

常见编译异常(必须处理)

  • SQLException//操作数据库时,查询表可能发生异常
  • IOException//操作文件时,发生的异常
  • FileNotFoundException T当操作一个不存在的文件时,发生异常
  • ClassNotFoundException//加载类,,而该类不存在时,异常
  • EOFException//操作文件,到文件末尾,发生异常
  • lllegalArguementException //参数异常
     

异常处理的两种方式

  • try-catch-finally:程序员在代码中捕获发生的异常,自行处理
  • throws:将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者就是JVM

 try - catch - final(Ctrl+Alt+t)

  • 如果异常发生了,则try块剩下的语句不会执行,直接进入到catch块.
  • 可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,比如(Exception在后,NullPointerException在前),如果发生异常,只会匹配一个catch
  • 可以进行 try-finally 配合使用, 这种用法相当于没有捕获异常, 因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异常, 都必须执行某个业务逻辑
  • 当catch和final都有return时,最后返回final的return
  • 当catch有return、final没有时,catch中的return值先保存在一个临时变量中,执行完final后再返回

throws 

  • 如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。
  • 在方法声明中用throws语句可以声明抛出异常的列表(逗号隔开),throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。
  • 对于编译异常,程序中必须处理,比如try-catch或者throws
  • 对于运行时异常,程序中如果没有处理,默认就是throws的方式处理
  • 子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常的类型的子类型[举例]
  • 在throws过程中,如果有方法 try-catch,就相当于处理异常,就可以不必throws
     

自定义异常

  • 定义类:自定义异常类名(程序员自己写)继承Exception或RuntimeException
  • 如果继承Exception,属于编译异常
  • 如果继承RuntimeException,属于运行异常(一般来说,继承RuntimeException,方便默认处理)
package zhh.chapter12;

import java.util.Scanner;

/**
 * @author longbownice
 * @version 1.0
 */
public class CustomException {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(true){
            int age=scanner.nextInt();

            try {
                if(age<0||age>120){
                    throw new AgeException("年龄应该在0-120,请重新输入");
                }else{
                    break;
                }
            } catch (AgeException e) {
                System.out.println(e.getMessage());
            }
        }
    }
//    print
//    155
//    年龄应该在0-120,请重新输入
//    10
}
class AgeException extends RuntimeException{
    public AgeException(String message) {
        super(message);
    }
}

 throw 和 throws 的区别

2、包装类

 八种包装类

包装类和基本数据的转换

  • jdk5前的手动装箱和拆箱方式,装箱:基本类型->包装类型,反之,拆箱
  • jdk5以后(含jdk5)的自动装箱和拆箱方式
  • 自动装箱底层调用的是valueOf方法,比如Integer.valueoof,其它包装类的用法类似
     

package zhh.chapter13;

/**
 * @author longbownice
 * @version 1.0
 *
 * 拆箱和装箱
 * 以integer和int为例
 */
public class Integer01 {
    public static void main(String[] args) {
        //jdk5以前,手动
        //装箱
        int i1=10;
        //方法一
        Integer integer1 = new Integer(i1);
        //方法二
        Integer integer2 = Integer.valueOf(i1);

        //拆箱
        int i2=integer1.intValue();

        //jdk5以后,手动
        int i3=20;
        //装箱,底层还是valueOf
        Integer integer=i3;
        //拆箱,底层还是intValue
        int i4=integer;

    }

}

包装类型和 String 类型的相互转换

package zhh.chapter13.wrapper;

/**
 * @author longbownice
 * @version 1.0
 *
 * 包装类型和 String 类型的相互转换
 * 以Integer为例
 */
public class WrapperVSString {
    public static void main(String[] args) {
        //Integer ->String
        Integer i1=1;//自动装箱
        //三种方法
        String s = i1 + "";
        String s1 = i1.toString();
        String s2 = String.valueOf(i1);

        //String ->Integer
        String s3 = "1234";
        int i = Integer.parseInt(s3);
        Integer integer = new Integer(s3);//构造器

        System.out.println("ok");
    }
}

Integer 类和 Character 类的常用方法

package zhh.chapter13.wrapper;

/**
 * @author longbownice
 * @version 1.0
 *
 * Integer 类和 Character 类的常用方法
 */
public class WrapperMethod {

    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE); //返回最小值,-2147483648
        System.out.println(Integer.MAX_VALUE);//返回最大值,2147483647

        System.out.println(Character.isDigit('a'));//判断是不是数字,false
        System.out.println(Character.isLetter('a'));//判断是不是字母,true
        System.out.println(Character.isUpperCase('a'));//判断是不是大写,false
        System.out.println(Character.isLowerCase('a'));//判断是不是小写,true
        System.out.println(Character.isWhitespace('a'));//判断是不是空格,false
        System.out.println(Character.toUpperCase('a'));//转成大写,A
        System.out.println(Character.toLowerCase('A'));//转成小写,a
    }
}

 Integer.valueOf方法详解

package zhh.chapter13.wrapper;

/**
 * @author longbownice
 * @version 1.0
 *
 * Integer.valueOf方法详解
 * 当有基本数据类型时,“==”判断的是值是否相同
 */
public class IntegerTest {

    public static void main(String[] args) {
        //从Integer.valueOf和IntegerCache类的源码可以看出
        //1. 如果 i 在 IntegerCache.low(-128)~IntegerCache.high(127),就直接从数组返回,
        // 地址和普通int一样
        //2. 如果不在 -128~127,就直接 new Integer(i)

        //由此可以得出
        //示例一
        Integer i1 = new Integer(127);
        Integer i2 = new Integer(127);
        System.out.println(i1 == i2);//F
        //示例二
        Integer i3 = new Integer(128);
        Integer i4 = new Integer(128);
        System.out.println(i3 == i4);//F
        //示例三
        Integer i5 = 127;//底层 Integer.valueOf(127)
        Integer i6 = 127;//-128~127
        System.out.println(i5 == i6); //T
        //示例四
        Integer i7 = 128;
        Integer i8 = 128;
        System.out.println(i7 == i8);//F
        //示例五
        Integer i9 = 127; //Integer.valueOf(127)
        Integer i10 = new Integer(127);
        System.out.println(i9 == i10);//F

        //示例六
        Integer i11=127;
        int i12=127;
        System.out.println(i11==i12); //T
        //示例七
        Integer i13=128;
        int i14=128;
        System.out.println(i13==i14);//T
    }
}


//以下是Integer.valueOf和IntegerCache类的源码
    /*
    public static Integer valueOf(int i) {
        if (i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high)
            return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)];
        return new Integer(i);
    }

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
     */

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值