进阶day04-throws关键字的作用

This commit is contained in:
2026-02-04 10:59:50 +08:00
parent 53f046e66e
commit 01858c81a9

View File

@@ -0,0 +1,38 @@
package com.inmind.throws03;
/*
throws关键字
throws:声明一个异常,提醒方法的调用者,该方法可能会抛出某些异常,但是也有可能不抛出异常
throw:真的抛出了一个真正的异常
throws关键字的语法格式
方法修饰符 返回值类型 方法名(参数列表) throws 异常名,异常名...{
方法体
}
注意点:
1.方法中如果抛出一个编译时异常,一定要处理(try-catch)或者声明出去
2.如果调用了一个声明了编译时异常的方法,那么也一定要处理(try-catch)或者声明出去
3.如果方法中没有异常出现,我们也是可以声明
*/
public class ThrowsDemo05 {
public static void main(String[] args) throws Exception {
method1();
method3();
System.out.println("程序结束");
}
public static void method1() throws Exception{
//抛出一个编译时异常
throw new Exception();
}
public static void method2() throws RuntimeException{
//抛出一个运行时异常
throw new RuntimeException();
}
public static void method3() throws Exception{
}
}