s-day05-throws关键字
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user