在 Java 中,异常用于处理程序执行期间发生的异常情况。您可以创建自定义异常并使用 try-catch 块或 throws 声明来处理异常。异常分为受检异常(编译器强制处理)和非受检异常(无需编译器处理)。本教程指导您创建自定义异常、处理受检异常(使用 try-catch 块)和非受检异常(使用 throws 声明)。
如何在 Java 中创建异常
在 Java 中,异常是用来处理在程序执行过程中发生的非正常情况的机制。异常类提供了关于错误或故障类型的信息,允许程序控制流针对这些情况作出反应。
在本教程中,您将学习:
1. 基本概念
Java 中的异常是 Throwable
类的实例,分为两种主要类型:
IOException
或 SQLException
。NullPointerException
或 ArrayIndexOutOfBoundsException
。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. 处理不同类型的异常
可以通过两种主要方式来处理异常:
try-catch
块的异常处理: 使用 try-catch
块来处理受检异常,当抛出异常时执行 catch
块中的代码。throws
声明: 使用 throws
声明来说明方法可能抛出的未受检异常,让调用方处理异常。实战案例:
考虑一个简单的客户管理系统。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.