From a43af9bd28b2c0b5c4cb6d441b52b5b64b10d004 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 4 Feb 2026 10:16:25 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day04-throw=E5=85=B3=E9=94=AE?= =?UTF-8?q?=E5=AD=97=E7=9A=84=E4=BD=9C=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/com/inmind/throw02/ThrowDemo03.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 javaSE-day05/src/com/inmind/throw02/ThrowDemo03.java diff --git a/javaSE-day05/src/com/inmind/throw02/ThrowDemo03.java b/javaSE-day05/src/com/inmind/throw02/ThrowDemo03.java new file mode 100644 index 0000000..9833b77 --- /dev/null +++ b/javaSE-day05/src/com/inmind/throw02/ThrowDemo03.java @@ -0,0 +1,34 @@ +package com.inmind.throw02; +/* +Java异常处理的五个关键字:try、catch、finally、throw、throws + throw关键字的作用: + 之前的代码中如果出现异常都是JVM创建并抛出,那么能不能自己抛出呢??? + + 可以,throw能够由java开发人员自己抛出一个异常 + 语法:throw new 异常名(); + + 为什么要自己抛出异常而不使用JVM的异常操作 呢?? + 我们要针对指定的异常,做出对应处理方案 + */ +public class ThrowDemo03 { + public static void main(String[] args) { + //定义整数数组 + int[] arr = {1, 2, 3, 4, 5}; + //定义出一个根据索引获取指定数组空间的值 + int result = getByIndex(arr,7); + System.out.println(result); + System.out.println("程序结束"); + } + + private static int getByIndex(int[] arr, int index) { + //当传入的索引值不合法时,我们自己主动抛出一个异常,交给调用者处理 + if (index < 0 || index > arr.length - 1) { + String msg = "您输入的索引不合法,当前数组的索引范围只能是0~"+(arr.length-1)+",但是您输入的索引为"+index; + throw new ArrayIndexOutOfBoundsException(msg); + } + + int result = arr[index]; + System.out.println("getByIndex方法正常执行"); + return result; + } +}