Java - бросай и лови в том же методе

У меня проблема с пониманием существующего кода. Я хотел бы знать, как 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 ответа

Решение

Ну давай проверим

    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(); 
 }

Помните, что "Попробовать поймать" означает: "Поймай это или верни" (кто-то другой поймает его, а если нет, то перейдет на главное и остановит ваш процесс:

1 2 3 будет выходной.

не 4, потому что исключение пойман в methodблок try-catch

Другие вопросы по тегам