【问题标题】:Java - throw and catch in same methodJava - 以相同的方法抛出和捕获
【发布时间】:2017-03-22 14:43:00
【问题描述】:

我无法理解现有代码。我想知道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 31 2 4

【问题讨论】:

  • 1 2 3 将被输出
  • 你能不自己试试运行吗?
  • 除非您将方法声明为静态,否则它不会编译。一旦你解决了这个问题,正如@findusl 所说,输出将是 1,2,3
  • 我同意@findusl ...method() 应该捕获并吞下异常。如果它重新抛出异常,您还会在输出中得到4
  • @kuba44 这不是你问的。

标签: java exception try-catch throw


【解决方案1】:

好吧,让我们检查一下:

    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first prints 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 throws IOException (it could throw it or not)
     try {
         System.out.println("2");  //<--It will print 2 and thow an IOException
         throw new IOException(); //<--now it throws it but as you're using a try catch it will catch it in this method
     }
     catch(IOException e) {//the exception is caught here and it so it will print 3
         System.out.println("3"); //<--Prints 3
     }
 }

现在,如果您在 method() 方法中删除您的 catch 子句,那么它会为您捕获它:

    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first prints 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(); 
 }

请记住,try-catch 的意思是:抓住它或扔掉它(其他人会抓住它,如果没有,它会转到 main 并停止你的进程)。

【讨论】:

  • “记住一个 Try catch 的意思是:抓住它或 TRHOW 它” - 好的,我知道。但我认为 throw 关键字会从method() 中运行程序。
  • 如果你没有在同一个方法中捕获到异常,它会这样做
【解决方案2】:

1 2 3 将是输出。

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

【讨论】:

  • 所以不会是 1 2 4 ?我认为抛出异常会被 main 方法捕获。
  • 在 main 方法中,没有传播异常,因为它在 method 的 try-catch 块中被捕获。请尝试使用您的代码进行试验,然后您就会清楚:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 2017-01-04
  • 2017-05-24
相关资源
最近更新 更多