try catch的使用

try catch的使用

在 Java 中,try-catch 语句用于异常处理。异常处理可以帮助我们在程序出现错误时,不会导致程序崩溃,而是采取一定的措施来处理错误。try-catch 语句是用于捕获并处理异常的机制。

基本语法

try {
    // 可能会抛出异常的代码块
} catch (ExceptionType1 e1) {
    // 处理异常类型 1 的代码
} catch (ExceptionType2 e2) {
    // 处理异常类型 2 的代码
} finally {
    // 无论是否发生异常,都会执行的代码(可选)
}
  • try 块中包含可能抛出异常的代码。
  • catch 块用于捕获和处理异常。一个 try 可以跟多个 catch 块,按顺序捕获不同类型的异常。
  • finally 块是可选的,无论是否发生异常,finally 中的代码都会执行,通常用于资源清理等操作。

1. 基本的 try-catch 例子

下面是一个简单的 try-catch 例子,展示了如何捕获并处理一个除零异常 (ArithmeticException):

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // 这里会抛出 ArithmeticException 异常
            System.out.println("结果是:" + result);
        } catch (ArithmeticException e) {
            System.out.println("捕获到异常:" + e.getMessage());  // 处理异常
        }

        System.out.println("程序继续执行...");
    }
}
运行结果:
捕获到异常:/ by zero
程序继续执行...

2. 多个 catch 块

可以使用多个 catch 块来捕获不同类型的异常,并做出相应的处理。比如,如果有多个可能的异常来源,我们可以分别处理每个不同的异常类型。

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = new int[2];
            numbers[10] = 5;  // 数组越界异常
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界异常:" + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("算术异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println("通用异常:" + e.getMessage());
        }
    }
}
运行结果:
数组越界异常: Index 10 out of bounds for length 2

3. 捕获父类异常

Java 中的异常有层次结构,某些异常是其他异常的子类。如果你在 catch 中按顺序写了父类异常类型,它会先捕获父类类型的异常,之后的子类异常就无法捕获了。因此,父类异常的 catch 块通常写在子类异常的后面。

public class CatchParentException {
    public static void main(String[] args) {
        try {
            String s = null;
            System.out.println(s.length());  // 会抛出 NullPointerException 异常
        } catch (Exception e) {
            System.out.println("捕获到异常:" + e.getMessage());  // 捕获父类异常
        } catch (NullPointerException e) {
            System.out.println("空指针异常:" + e.getMessage());  // 这个代码永远不会执行
        }
    }
}
运行结果:
捕获到异常:null

4. finally 块

finally 块用于无论异常是否发生,都会执行的代码块。它常用于释放资源,如关闭数据库连接、文件流等。finally 块是可选的,但如果存在,它一定会被执行。

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("执行 try 块");
            int result = 10 / 2;  // 没有异常
            System.out.println("结果是:" + result);
        } catch (Exception e) {
            System.out.println("捕获异常");
        } finally {
            System.out.println("执行 finally 块");
        }
    }
}
运行结果:
执行 try 块
结果是:5
执行 finally 块

5. 捕获多个异常(JDK 7 及以上)

从 JDK 7 开始,Java 允许使用 |(管道符号)在一个 catch 块中捕获多种异常类型。这样可以减少代码重复,提高可读性。

public class MultiCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = new int[2];
            numbers[10] = 5;  // 数组越界异常
            int result = 10 / 0;  // 除零异常
        } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
            System.out.println("捕获到异常:" + e.getMessage());
        }
    }
}
运行结果:
捕获到异常: Index 10 out of bounds for length 2

6. 抛出异常(throw)

try-catch 语句中,如果需要主动抛出异常,可以使用 throw 关键字。throw 用于显式地抛出一个异常。

public class ThrowExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);  // 主动抛出异常
        } catch (ArithmeticException e) {
            System.out.println("捕获到异常:" + e.getMessage());
        }
    }

    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("除数不能为零");
        }
        return a / b;
    }
}
运行结果:
捕获到异常:除数不能为零

7. 自定义异常

你可以定义自己的异常类,继承 Exception 类,并在 try-catch 中捕获它。

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new CustomException("这是一个自定义异常");
        } catch (CustomException e) {
            System.out.println("捕获到自定义异常:" + e.getMessage());
        }
    }
}
运行结果:
捕获到自定义异常:这是一个自定义异常

总结

  • try-catch 用于捕获和处理程序中的异常,防止程序崩溃。
  • 使用多个 catch 可以捕获不同类型的异常。
  • finally 块总会执行,通常用于资源清理。
  • JDK 7 引入了多异常捕获的简化语法,可以在一个 catch 块中处理多个异常类型。
  • 可以通过 throw 抛出异常,也可以自定义异常类。

通过合理的使用 try-catch,你能够提高程序的健壮性,并更好地处理错误情况。 [Something went wrong, please try again later.]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值