在 java 中,异常用于处理程序执行期间发生的异常情况。您可以创建自定义异常并使用 try-catch 块或 throws 声明来处理异常。异常分为受检异常(编译器强制处理)和非受检异常(无需编译器处理)。本教程指导您创建自定义异常、处理受检异常(使用 try-catch 块)和非受检异常(使用 throws 声明)。
如何在 Java 中创建异常
在 Java 中,异常是用来处理在程序执行过程中发生的非正常情况的机制。异常类提供了关于错误或故障类型的信息,允许程序控制流针对这些情况作出反应。
在本教程中,您将学习:
立即学习“Java免费学习笔记(深入)”;
1. 基本概念
Java 中的异常是 Throwable 类的实例,分为两种主要类型:
2. 创建自定义异常
您可以通过扩展 Exception 或 RuntimeException 来创建自己的自定义异常。例如,让我们创建一个名为 CustomerNotFoundException 的异常:
public class CustomerNotFoundException extends RuntimeException { private final String customerId; public CustomerNotFoundException(String customerId) { super("Customer with ID " + customerId + " not found."); this.customerId = customerId; } public String getCustomerId() { return customerId; } }
3. 处理不同类型的异常
可以通过两种主要方式来处理异常:
实战案例:
考虑一个简单的客户管理系统。CustomerService 类有一个方法 findById(),该方法用于获取具有给定 ID 的客户:
public class CustomerService { public Customer findById(String customerId) { // 检查数据库中是否存在客户 if (customer == null) { throw new CustomerNotFoundException(customerId); } return customer; } }
在调用 findById() 方法时,您可以使用 try-catch 块来处理 CustomerNotFoundException 异常:
try { Customer customer = customerService.findById("1234"); } catch (CustomerNotFoundException e) { // 处理客户未找到的情况 System.out.println("Customer not found: " + e.getCustomerId()); }
alternatively, you can use the throws declaration in the calling method to indicate that the exception might be thrown:
public void findCustomer(String customerId) throws CustomerNotFoundException { Customer customer = customerService.findById(customerId); }
In this case, the calling method must handle the exception or declare it in its own throws declaration.
以上就是如何在 Java 中创建异常?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号