From ddd9a7cb97fc26d782cbf2a8a4a33dd9d2409bf9 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 4 Feb 2026 11:26:32 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day04-try...catch=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86=E6=96=B9=E5=BC=8F=E4=BB=A5=E5=8F=8A?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inmind/try_catch04/TryCatchDemo06.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java diff --git a/javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java b/javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java new file mode 100644 index 0000000..54ee502 --- /dev/null +++ b/javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java @@ -0,0 +1,42 @@ +package com.inmind.try_catch04; +/* +try...catch异常处理方式以及执行流程 + + 之前throws关键字只是将异常声明出去,没有真正地处理,那么如何真的解决掉异常呢??? + + 1.try...catch的作用:真的处理掉了异常,JVM就不会再得到异常,程序会正常执行 + 2.try...catch语法: + try{ + 可能会出现异常的代码 + }catch(指定异常类名 变量名){ + 捕获了异常之后,异常处理代码 + } + + 3.try...catch执行流程: + a.当try中的代码,如果没有发生异常,那么try中的代码正常执行结果,并且catch就不会执行. + b.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了, + 如果catch捕获到异常,catch后面的代码会执行,程序正常执行 + c.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了, + 如果catch没有捕获到异常,catch后面的代码不会执行,异常交给JVM,程序异常终止 + */ +public class TryCatchDemo06 { + public static void main(String[] args) { + try { + System.out.println("try---------start【1】"); + int[] arr = {1, 2, 3, 4, 5}; + int result = getByIndex(arr, 6); + System.out.println(result); + System.out.println("try---------end【2】"); + } catch (NullPointerException e) { + System.out.println(e); + System.out.println("处理了索引越界异常"); + System.out.println("catch---------【3】"); + } + System.out.println("程序结束------【4】"); + } + + private static int getByIndex(int[] arr, int index) { + int result = arr[index];//JVM只会创建越界异常 + return result; + } +}