Java中throw和throws的区别

x33g5p2x  于2022-05-22 转载在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(481)

throw和throws作为Java中两种异常抛出关键字,虽然两个长的很像,但是却有着很大的区别。

区别1:
  1. throws:
  2. 跟在方法声明后面,后面跟的是异常类名
  3. throw:
  4. 用在方法体内,后面跟的是异常类对象名
  1. public static void method() throws ArithmeticException {// 跟在方法声明后面,后面跟的是异常类名
  2. int a=10;
  3. int b=0;
  4. if(b==0) {
  5. throw new ArithmeticException();用在方法体内,后面跟的是异常类对象名
  6. }else {
  7. System.out.println(a/b);
  8. }
  9. }
  10. }
区别2:
  1. throws:
  2. 可以跟多个异常类名,用逗号隔开
  3. throw:
  4. 只能抛出一个异常对象名
  1. public static void method() throws ArithmeticException,Exception {//跟多个异常类名,用逗号隔开
  2. int a=10;
  3. int b=0;
  4. if(b==0) {
  5. throw new ArithmeticException();// 只能抛出一个异常对象名
  6. }else {
  7. System.out.println(a/b);
  8. }
  9. }
  10. }
区别3:
  1. throws:
  2. 表示抛出异常,由该方法的调用者来处理
  3. throw:
  4. 表示抛出异常,由该方法体内的语句来处理
  1. public class throwandthrows {
  2. public static void main(String[] args) {
  3. try {
  4. method();//由该方法的调用者来处理
  5. }catch (ArithmeticException e) {
  6. e.printStackTrace();
  7. }
  8. }
  9. public static void method() throws ArithmeticException {
  10. int a=10;
  11. int b=0;
  12. if(b==0) {
  13. throw new ArithmeticException();//由该方法体内的语句来处理
  14. }else {
  15. System.out.println(a/b);
  16. }
  17. }
  18. }
区别4:
  1. throws:
  2. throws表示有出现异常的可能性,并不一定出现这些异常
  3. throw:
  4. throw则是抛出了异常,执行throw一定出现了某种异常

我们向上面例子代码里throws一个IndexOutOfBoundsException异常,编译发现并没有报错,这就体现了throws表示有出现异常的可能性

  1. public class throwandthrows {
  2. public static void main(String[] args) {
  3. try {
  4. method();
  5. }catch (ArithmeticException e) {
  6. e.printStackTrace();
  7. }
  8. }
  9. public static void method() throws ArithmeticException,IndexOutOfBoundsException {
  10. int a=10;
  11. int b=0;
  12. if(b==0) {
  13. throw new ArithmeticException();
  14. }else {
  15. System.out.println(a/b);
  16. }
  17. }
  18. }

相关文章

最新文章

更多