s-day05--throws关键字的介绍
This commit is contained in:
@@ -0,0 +1,35 @@
|
|||||||
|
package com.inmind.exception01;
|
||||||
|
/*
|
||||||
|
6.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
|
||||||
|
//调用了一个声明了Exception编译时异常的方法
|
||||||
|
method1();
|
||||||
|
method2();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void method2() throws Exception {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void method1() throws Exception{//只要不是RuntimeException本身或它的子类,其他都是编译时异常
|
||||||
|
//真的抛出一个编译时异常
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user