* throw和throws的区别:
*1.位置不同
* throw:方法的内部
* throws:方法的声明处
* 2.内容不同
* throw new 异常();
* throws+异常类型的对象(可以有多个类型 用,连接)
* 3.作用不同
* throw:异常的源头,制造异常
* throws:声明异常,告诉方法的调用者,这个方法可能会出现的异常,然后调用者对这些异常进行处理
*/
public class ThrowsDemo {
private String name = "";
private int age = 0;
private String gender = "";
public static void main(String[] args) {
test1();
}
public static void test1() {
try {
System.out.println(1/0);
test2();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test2() throws Exception {
System.out.println(1/0);
test3();
}
public static void test3() throws Exception {
System.out.println(1/0);
test4();
}
public static void test4() throws Exception {
System.out.println(1/0);
}
}
:自定义异常
自定义异常:
* 在java的API中提供了非常多的异常类,但是在某些情况下不太满足我们的需求,
* 此时我们就要自定义异常
* 步骤:
* 1.继承Exception
* 2.自定义实现的构造方法
* 3.需要使用的时候,使用throw new自定义异常的名称
* 什么时候需要使用?
* 一般情况下不需要使用
* 但是有的公司要求异常格式统一规范时必须是自己实现
java throw 和throws的区别
最新推荐文章于 2024-05-13 15:45:00 发布