From 4d5deea28bd5e7c49689bd7b2fa1d7b92d8bcfde Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 5 Aug 2026 10:51:08 +0800 Subject: [PATCH] =?UTF-8?q?s-day05-=E8=BF=90=E8=A1=8C=E6=97=B6=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=92=8C=E7=BC=96=E8=AF=91=E6=97=B6=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E7=9A=84=E5=8C=BA=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inmind/exception_trycatch02/Demo08.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 s-day05/src/com/inmind/exception_trycatch02/Demo08.java diff --git a/s-day05/src/com/inmind/exception_trycatch02/Demo08.java b/s-day05/src/com/inmind/exception_trycatch02/Demo08.java new file mode 100644 index 0000000..4e7109b --- /dev/null +++ b/s-day05/src/com/inmind/exception_trycatch02/Demo08.java @@ -0,0 +1,39 @@ +package com.inmind.exception_trycatch02; +/* +运行时异常和编译时异常的区别 +运行时异常(RuntimeException):属于非检查型异常,无需强制处理,可以通过优化代码逻辑,避免异常。 +编译时异常(非RuntimeException):属于检查型异常,在编写阶段,可能出现语法问题必须处理,需要程序员预见并处理可能的异常情况,可以通过try-catch或throws处理 + +总结:编写代码时,编译时异常必须处理,而运行时异常,可以选择性地处理 + +一个方法中的异常可以有2种处理方式: + 1.throws 声明出去,交给别人处理 + 2.try-catch 自己处理 +在main方法顶层,真正能处理掉异常的只有try-catch + */ +public class Demo08 { + public static void main(String[] args) { + method1(); + + try { + method2(); + } catch (Exception e) { + System.out.println("处理了编译时异常"); + } + System.out.println("程序结束"); + } + + private static void method2() throws Exception{ + throw new Exception(); + } + + private static void method1() { + try { + throw new RuntimeException("抛出一个运行时异常"); + } catch (RuntimeException e) { + System.out.println("处理了运行时异常"); + } + } + + +}