定义一个功能,进行除法运算例如(div(int x,int y))如果除数为0,进行处理。
功能内部不想处理,或者处理不了。就抛出使用throw new Exception("除数不能为0"); 进行抛出。抛出后需要在函数上进行声明,告知调用函数者,我有异常,你需要处理如果函数上不进行throws 声明,编译会报错。例如:未报告的异常 java.lang.Exception;必须对其进行捕捉或声明以便抛出throw new Exception("除数不能为0");
public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。
if (y == 0) {
throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
}
System.out.println(x / y);
System.out.println("除法运算");
}
5:main方法中调用除法功能
调用到了一个可能会出现异常的函数,需要进行处理。
1:如果调用者没有处理会编译失败。
如何处理声明了异常的函数。
1:try{}catch(){}
public static void main(String[] args) {
try {
div(2, 0);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("over");
}
public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。
if (y == 0) {
throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
}
System.out.println(x / y);
System.out.println("除法运算");
}
}
2:继续抛出throws
class Demo9 {
public static void main(String[] args) throws Exception {
div(2, 0);
System.out.println("over");
}
public static void div(int x, int y) throws Exception { // 声明异常,通知方法调用者。
if (y == 0) {
throw new Exception("除数为0"); // throw关键字后面接受的是具体的异常的对象
}
System.out.println(x / y);
System.out.println("除法运算");
}
}
throw和throws的区别
//throws 处理
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
obj.wait();
}
public static void main(String[] args) {
//try catch 处理
Object obj = new Object();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
总结
原文:https://www.cnblogs.com/gzgBlog/p/13588896.html