throw抛出异常后程序会怎样中断
使用 throw 语句抛出异常时,当前方法会立即停止执行并向上层调用者传递该异常对象。如果上层没有捕获处理,程序将终止运行。在测试中,可以通过验证代码是否到达特定行或使用断言来确认逻辑的中断点。

为了演示这一过程,我们定义一个简单的自定义异常类 InvalidInputException,并在一个服务类中使用它。当输入为负数时,抛出异常;否则返回结果。测试用例将分别覆盖正常路径和异常路径。
public class InvalidInputException extends Exception { public InvalidInputException(String message) { super(message); } }
public class CalculatorService { public int add(int a, int b) throws InvalidInputException { if (a <p>预期结果:当输入为正数时,<code>add</code> 方法返回两数之和;当任一输入为负数时,抛出 <code>InvalidInputException</code>,后续代码不再执行。</p><h2>如何捕获并处理自定义异常</h2><p>在 Java 中,可以使用 <code>try-catch</code> 块来捕获并处理自定义异常。捕获后,可以记录日志、返回默认值或进行其他恢复操作。测试时应验证异常被正确捕获且程序未崩溃。</p><p><img src="https://img.php.cn/upload/article/001/242/473/179513865038678.png?x-oss-process=image/resize,p_40" alt="Java 自定义异常怎么用异常测试验证逻辑"></p><p>以下代码展示了如何在客户端代码中捕获 <code>InvalidInputException</code>。如果发生异常,打印错误信息并返回 -1 作为默认值。测试将验证异常处理后的返回值是否符合预期。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="FilePond 灵活的 JavaScript 文件上传库" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库" class="overflowclass">FilePond 灵活的 JavaScript 文件上传库</a>
<p class="overflowclass">FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><pre class="brush:php;toolbar:false;">public class Client { public static void main(String[] args) { CalculatorService service = new CalculatorService(); try { int result = service.add(-5, 3); System.out.println("Result: " + result); } catch (InvalidInputException e) { System.out.println("Error: " + e.getMessage()); System.out.println("Default value returned."); } } }
预期结果:控制台输出 "Error: Negative input not allowed" 和 "Default value returned.",程序继续运行而不崩溃。
测试时如何验证异常的具体消息内容
在单元测试中,可以使用 JUnit 的 @Test(expected = ...) 注解或 assertThrows 方法来验证抛出的异常类型及其消息内容。这有助于确保异常携带的信息准确无误,便于调试和问题定位。
以下是一个使用 JUnit 5 的测试示例,验证 CalculatorService.add 方法在输入负数时抛出的异常消息是否为 "Negative input not allowed"。
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertThrows; public class CalculatorServiceTest { @Test void testAddWithNegativeInput() { CalculatorService service = new CalculatorService(); InvalidInputException exception = assertThrows(InvalidInputException.class, () -> service.add(-5, 3)); assertEquals("Negative input not allowed", exception.getMessage()); } }
预期结果:测试通过,确认抛出了 InvalidInputException 且消息内容匹配。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










