Java - 使用相同的方法抛出和捕获

时间:2017-03-22 14:43:01

标签: java exception try-catch throw

我对理解现有代码有疑问。我想知道Java如何管理抛出异常并以相同的方法捕获它。我无法在其他问题中找到它,所以我预备了一些例子。 Java中代码下面运行的输出是什么?

public static void main(String [ ] args) {
     try{
         System.out.println("1");
         method();
     }
     catch(IOException e) {
         System.out.println("4");
     }
}

public static void method() throws IOException {
     try {
         System.out.println("2");
         throw new IOException();
     }
     catch(IOException e) {
         System.out.println("3");
     }
 }

1 2 3 1 2 4

2 个答案:

答案 0 :(得分:4)

好吧,让我们检查一下

    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first print 1
             method();  //<--Then it will call your method here
         }
         catch(IOException e) { //<---Won't catch anything because you caught it already
             System.out.println("4");
         }
    }

public static void method() throws IOException { //<--Your Signature contains a trows IOException (it could trhow it or not)
     try {
         System.out.println("2");  //<--It will print 2 and thows an IOException
         throw new IOException(); //<--now it trows it but as you're using a try catch it will catch it in this method
     }
     catch(IOException e) {//it caught the exception in spite or trhow it so it will print 3
         System.out.println("3"); //<--Prints 3
     }
 }

现在,如果您删除此类Catch,现在它将为您捕获

    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first print 1
             method();  //<--Then it will call your method here
         }
         catch(IOException e) { //<---It will catch the Exception and print 4
             System.out.println("4");
         }
    }

public static void method() throws IOException { //<--Your Signature contains a trows IOException (it could trhow it or not)
         System.out.println("2");  //<--It will print 2 and thows an IOException
         throw new IOException(); 
 }

记住一个尝试捕获意味着:抓住它或者它是什么东西(其他人会抓住它,如果不是它会去主要并停止你的过程:9

答案 1 :(得分:1)

1 2 3 将是输出。

不是 4 ,因为method的try-catch块中捕获了异常