在真实编程环境中,定义方法的时候可以使用 throws 关键字声明,使用 throws 关键字表示该方法不处理异常,但是遇到异常的时候抛出去,将异常给调用它的类处理。
public 返回值 方法名称(参数列表...) throws 异常类{}
方法中,在处理异常的时候,除了 try…catch 以外还可以使用 throws 抛出异常信息。将异常信息抛出调用它的方法来处理。
定义一个抛出异常的测试类
package com.haicoder.net.haithrow;
public class ThrowsTest {
public int div(int num1, int num2) throws Exception {
return num1 / num2;
}
}
定义一个调用类
package com.haicoder.net.haithrow;
public class TestMain {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)");
ThrowsTest throwsTest = new ThrowsTest();
try {
throwsTest.div(1, 0);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束");
}
}
运行结果如下
div 方法上面 throws Exception。在调用 div 方法的时候,需要进行 try…catch 或者在调用这个方法的方法体上面继续将异常抛出,不然编译不会通过。java 语言如果异常信息一直向上抛,那么最终会给 jvm 进行处理。jvm 收到异常后会终止程序运行。
throws 是系统遇到异常信息时自动向调用方抛出,throw 是研发自己写代码的时候人为的将异常信息抛出,在人为抛出异常的时候,只需要排除异常的实例化对象就可以。
package com.haicoder.net.haithrow;
public class ThrowsTest {
public void throwException() {
try {
throw new Exception("这个是自己抛出的异常");
} catch (Exception e) {
e.printStackTrace();
}
}
}
定义调用类
package com.haicoder.net.haithrow;
public class TestMain {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)");
ThrowsTest throwsTest = new ThrowsTest();
try {
throwsTest.throwException();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束");
}
}
运行结果如下
throw 一般的不会单独使用,要么被 try…catch 住,要么会在调用的方法体上面拥有 throws 关键字,将异常信息抛出去,给调用它的方法处理。
throws 加在方法体后面,它可以指定抛出的异常信息,让调用它的方法体处理它的异常。throw 可以抛自己定义的异常,throw 一般与 try…catch… 或者 throws 一起使用,不会单独使用。