功能内部不想处理,或者处理不了。就抛出使用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("除法运算"); }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的区别 1. 相同:都是用于做异常的抛出处理的。 2. 不同点: 1. 使用的位置: throws 使用在函数上,throw使用在函数内 2. 后面接受的内容的个数不同: 1. throws 后跟的是异常类,可以跟多个,用逗号隔开。 2. throw 后跟异常对象。
//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(); } }