美文网首页
throws 和 throw

throws 和 throw

作者: 邢昱 | 来源:发表于2017-05-22 15:13 被阅读0次

    我们一般用到throw都是因为我们自己写了一种exception然后自己把它扔出去 但是我觉得就是其他的exception也是别人写好然后throw然后我们的代码运行程序的时候触发出来的

    对于RuntimeException来说 因为一般都是逻辑上的问题 编译也给你过

    但是如果是其他的exception的话 一定要用try-catch处理 或者声明throws 编译才给你过的

    throws的意思是说我这个method有可能会出exception然后我不处理 谁调用我谁处理 所以凡是调用了它的又没有用try-catch处理的method都要标记throws

    最后再记录一个看起来很奇怪的throws

     1 import java.util.Scanner;
     2 import java.io.*;
     3 
     4 public class DisplayFile{
     5   public static void main(String[] args)  throws IOException
     6   {
     7     String fileName;
     8     Scanner nameReader = new Scanner(System.in);
     9     System.out.println("Enter a file name");
    10     fileName = nameReader.nextLine();
    11     Scanner scan = new Scanner(new FileReader(fileName));
    12     while(scan.hasNext()){
    13       System.out.println(scan.nextLine());
    14     }
    15     scan.close();
    16   }
    17 }
    

    这里就是说它已经是main method了 它还在甩锅 这个是一个比较不负责任的写法 这样写强行过了个编译 但是 万一真的出了一个exception (好吧我也不知道会怎么样)

    相关文章

      网友评论

          本文标题:throws 和 throw

          本文链接:https://www.haomeiwen.com/subject/qtpbxxtx.html