From 79bebc52a54274062e8f2b11e8d68c831c654f73 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 5 Aug 2026 09:48:15 +0800 Subject: [PATCH] =?UTF-8?q?s-day05-throws=E5=85=B3=E9=94=AE=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/inmind/exception01/ThrowsDemo05.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 s-day05/src/com/inmind/exception01/ThrowsDemo05.java diff --git a/s-day05/src/com/inmind/exception01/ThrowsDemo05.java b/s-day05/src/com/inmind/exception01/ThrowsDemo05.java new file mode 100644 index 0000000..9437155 --- /dev/null +++ b/s-day05/src/com/inmind/exception01/ThrowsDemo05.java @@ -0,0 +1,38 @@ +package com.inmind.exception01; +/* +throws关键字 +throws:声明一个异常,提醒方法的调用者,指定方法可能会抛出某些异常,但是也可能不抛异常 +throw:真的抛出一个真正的异常 + +throws关键字的语法格式: +方法修饰符 返回值类型 方法名(参数列表) throws 异常名1,异常名2.... { + 方法体 +} + +注意点: +1.方法中如果抛出一个编译时异常,一定要处理(try-catch)或throws声明出去 +2.如果调用了一个声明了编译时异常的方法,那么当前方法中也一定要处理try-catch)或throws声明出去 +3.如果一个方法中没有异常,我们也是可以声明异常的 + +总结:throws的作用什么?? + 提醒方法调用者,指定方法,可能出异常,当我们想将本方法中可能出现的异常交给别人去处理,那么就使用throws + */ +public class ThrowsDemo05 { + public static void main(String[] args) throws Exception {//主方法也不处理,交给JVM处理 + int i = 10; + int j = 20; +// method1(); + method2(); + System.out.println("程序结束"); + } + + private static void method2() throws Exception { + System.out.println("method2方法执行了"); + } + + //该方法声明可能会出现Exception,自己不处理,交给调用者处理 + private static void method1() throws Exception{ + //手动抛出一个编译时异常 + throw new Exception(); + } +}