尝试编写包含多个 Catch 块的 Java Try 代码

发布时间:2025-02-07 15:31:34 作者:小樊
来源:亿速云 阅读:89

在Java中,一个try代码块可以包含多个catch块来处理不同类型的异常

public class MultipleCatchBlocks {
    public static void main(String[] args) {
        try {
            // Code that might throw an exception
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle ArithmeticException
            System.out.println("Error: Division by zero is not allowed.");
        } catch (NullPointerException e) {
            // Handle NullPointerException
            System.out.println("Error: Null value is not allowed.");
        } catch (Exception e) {
            // Handle any other exceptions
            System.out.println("Error: An unexpected error occurred.");
        } finally {
            // Code that will always execute
            System.out.println("This block will always execute.");
        }
    }

    public static int divide(int a, int b) throws ArithmeticException {
        return a / b;
    }
}

在这个示例中,我们尝试执行除法操作,该操作可能会抛出ArithmeticException(当除数为零时)或NullPointerException(如果传入的参数为null)。我们还添加了一个通用的Exceptioncatch块来处理其他可能的异常。最后,我们使用finally块来确保某些代码始终会执行,无论是否发生异常。

推荐阅读:
  1. puppeteer 尝试
  2. Java编写代码的规范有哪些?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Try 语句能处理运行时异常吗

下一篇:Java Try-With-Resources 会自动关闭哪些资源

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》