throw和throws的区别

参考答案

throw和throws的区别:

throw

  • 位于方法体内部,可作为单独语句使用;
  • 表示方法内抛出某种异常对象(只能是一个);
  • 用于程序员自行产生并抛出异常;
  • 异常对象是非 RuntimeException,需要在方法申明时加上该异常的抛出。即:需添加throws 语句,或在方法体内try catch 处理该异常,否则编译时会报错;
  • 执行到 throw 语句时,后面的语句块不再执行。

throws

  • 用于声明在该方法内抛出了异常;
  • 方法的定义上,使用 throws 表示这个方法可能抛出某些异常(可以有多个);
  • 不可以单独使用,只能跟在方法参数列表的后面;
  • 需由方法的调用者进行异常处理。

实例:

  1. package constxiong.interview;
  2. import java.io.IOException;
  3. public class TestThrowsThrow {
  4. public static void main(String[] args) {
  5. testThrows();
  6. Integer i = null;
  7. testThrow(i);
  8. String filePath = null;
  9. try {
  10. testThrow(filePath);
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. /**
  16. * 测试 throws 关键字
  17. * @throws NullPointerException
  18. */
  19. public static void testThrows() throws NullPointerException {
  20. Integer i = null;
  21. System.out.println(i + 1);
  22. }
  23. /**
  24. * 测试 throw 关键字抛出 运行时异常
  25. * @param i
  26. */
  27. public static void testThrow(Integer i) {
  28. if (i == null) {
  29. throw new NullPointerException();//运行时异常不需要在方法上申明
  30. }
  31. }
  32. /**
  33. * 测试 throw 关键字抛出 非运行时异常,需要方法体需要加 throws 异常抛出申明
  34. * @param i
  35. */
  36. public static void testThrow(String filePath) throws IOException {
  37. if (filePath == null) {
  38. throw new IOException();//非运行时异常,需要方法体需要加 throws 异常抛出申明
  39. }
  40. }
  41. }

 

以上,是Java面试题【throw和throws的区别】的参考答案。

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧