java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java包装类与异常处理

Java包装类与异常处理的过程

作者:辞忧要靠自己

本文介绍了Java中包装类和异常处理的概念,解析了它们的用途和使用方法,包装类主要用于将基本数据类型转换为对象,解决面向对象编程中的限制;异常处理机制则帮助程序优雅地处理运行时错误,包括常见异常类型、异常处理语句及自定义异常的使用

在 Java 开发中,包装类异常处理是两个核心且高频的知识点。它们分别解决了基本数据类型的对象化问题,以及程序运行时的错误处理问题。

本文将结合代码示例,深入解析这两个概念,帮助你更好地理解和运用。

一、包装类:让基本数据类型 “对象化”

1. 什么是包装类?

Java 中的数据类型从本质上分为两类:

为了让基本数据类型也能以对象的形式存在,Java 提供了一组包装类,专门用来创建与 8 种基本数据类型对应的对象。

2. 基本数据类型与包装类的对应关系

基本数据类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

这些包装类全部存放于 java.lang 包中,它们的继承关系如下:

public class Test {
    public static void main(String[] args) {
        byte b = 1;
        Byte byt = new Byte(b);
        
        short s = 2;
        Short shor = new Short(s);
        
        int i = 3;
        Integer integer = new Integer(i);
        
        long l = 4;
        Long lon = new Long(l);
        
        float f = 5.5f;
        Float flo = new Float(f);
        
        double d = 6.6;
        Double dou = new Double(d);
        
        char cha = 'J';
        Character charac = new Character(cha);
        
        boolean bo = true;
        Boolean bool = new Boolean(bo);
    }
}

注意:从 Java 5 开始,引入了自动装箱(Autoboxing)功能,编译器会自动完成这个转换,例如 Integer i = 3;

拆箱:包装类 → 基本数据类型

将包装类对象转换回对应的基本数据类型。

public class Test {
    public static void main(String[] args) {
        byte b = 1;
        Byte byt = new Byte(b);
        byte b1 = byt.byteValue();
        
        short s = 2;
        Short shor = new Short(s);
        short i1 = shor.shortValue();
        
        int i = 3;
        Integer integer = new Integer(i);
        int i2 = integer.intValue();
        
        long l = 4;
        Long lon = new Long(l);
        long l1 = lon.longValue();
        
        float f = 5.5f;
        Float flo = new Float(f);
        float v = flo.floatValue();
        
        double d = 6.6;
        Double dou = new Double(d);
        double v1 = dou.doubleValue();
        
        char cha = 'J';
        Character charac = new Character(cha);
        char c = charac.charValue();
        
        boolean bo = true;
        Boolean bool = new Boolean(bo);
        boolean b2 = bool.booleanValue();
    }
}

注意:同样,Java 5 也引入了自动拆箱(Unboxing)功能,例如 int i = new Integer(3);

二、异常处理:让程序 “优雅” 地应对错误

1. 什么是异常?

Java 中的错误可以分为两大类:

异常就是 Java 提供的一套机制,用来专门处理各种运行时错误。它会将具体的错误信息以及出错位置统一告知程序员,帮助我们快速定位和解决问题。

2. 常见的异常类型

Java 内置了丰富的异常类,以下是几个最常见的:

System.out.println(10 / 0); // 抛出此异常
System.out.println(Class.forName("Test2"));
public void test(Integer integer) {
    System.out.println(integer);
}
// 当通过反射调用此方法并传入字符串 "1" 时会抛出此异常
int[] array = {1, 2, 3};
System.out.println(array[3]); // 数组长度为3,索引最大为2
Integer num = null;
System.out.println(num.equals(1));
Integer integer = new Integer("a"); // 字符串 "a" 无法转换为整数

3. 异常的使用:try-catch-finally

Java 提供了 try-catch-finally 语句块来捕获和处理异常。

public class Test3 {
    public static void test3(String str) {
        Integer integer = null;
        try {
            integer = Integer.valueOf(str);
        } catch (Exception e) {
            // 打印异常信息
            System.out.println(e.getMessage());
        }
    }
}
public class Test {
    public static void main(String[] args) throws Exception {
        System.out.println(test());
    }

    public static int test() {
        try {
            System.out.println("try");
            return 10;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally...");
            return 20;
        }
    }
}
// 输出:
// try
// finally...
// 20

注意:如果 trycatch 中有 return 语句,finally 块仍然会在方法返回前执行。如果 finally 中也有 return,则会覆盖 trycatch 中的返回值。

4.throw和throws:主动抛出异常

throwthrows 是 Java 在处理异常时使用的关键字,都用来抛出异常,但是使用方式和表示的含义完全不同。

public class Test {
    public static void main(String[] args) throws Exception {
        String str = "Java";
        if (str.equals("Java")) {
            // 主动创建并抛出一个 NumberFormatException
            throw new NumberFormatException();
        } else {
            int num = Integer.parseInt(str);
        }
    }
}
public class Test {
    public static void main(String[] args) throws Exception {
        try {
            test();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    // 声明此方法可能会抛出 NumberFormatException
    public static void test() throws NumberFormatException {
        String str = "Java";
        int num = Integer.parseInt(str);
    }
}

5. 自定义异常

当内置的异常类无法满足业务需求时,我们可以创建自定义异常。自定义异常类需要继承自 Exception 类(或其子类)。

示例:定义一个方法,对传入的参数进行 ++ 操作并返回结果,同时要求参数传入的必须是整数类型,如果不是整数类型则抛出自定义异常。

// 1. 定义自定义异常类,继承 Exception
public class NumberException extends Exception {
    public NumberException(String message) {
        super(message);
    }
}

// 2. 使用自定义异常
public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        try {
            int add = test.add("a"); // 传入字符串,不是整数
            System.out.println(add);
        } catch (NumberException e) {
            // 捕获并处理自定义异常
            e.printStackTrace();
        }
    }

    // 方法声明可能抛出 NumberException
    public int add(Object object) throws NumberException {
        if (!(object instanceof Integer)) {
            // 主动抛出自定义异常
            throw new NumberException("传入的参数不是整数类型");
        } else {
            int num = (int) object;
            return ++num;
        }
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文