
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.概念
如果方法声明的是Exception类型的异常或者是Checked Exception异常,要求方法的调用处必须做处理。
(1)继续使用throws向上(方法的调用处)声明
(2)使用try-catch-finally进行处理
2.语法
1 2 | [(修饰符)](返回值类型)(方法名)([参数列表])[throws(异常类)]{......}
public void function () throws Exception{......}
|
3.实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super (msg);
}
}
public class Demo3 {
public static void main(String[] args) {
try {
test();
} catch (MyException e) {
System.out.println( "Catch My Exception" );
e.printStackTrace();
}
}
public static void test() throws MyException{
try {
int i = 10/0;
System.out.println( "i=" +i);
} catch (ArithmeticException e) {
throw new MyException( "This is MyException" );
}
}
}
|
以上就是java中throws的使用方法,当我们需要声明异常时选择throws,反之抛出就选择throw,掌握了这个要点大家就不会在使用时出错了。