Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - throw and catch in same method

I have problem with understand existing code. I would like to know how Java manage throw exception and catch it in same method. I can't find it in other question so I preapare example. What will be output of run below code in 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");
     }
 }

It will be 1 2 3 or 1 2 4?

like image 610
kuba44 Avatar asked Feb 04 '23 20:02

kuba44


2 Answers

Well, let's check:

    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
     }
 }

Now, if you remove your catch clause in the method() method for something like this, now it will catch it for you:

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

Remember, a try-catch means: CATCH IT OR THROW IT (someone else will catch it, and if not it will go to the main and stop your process).

like image 143
Yussef Avatar answered Feb 07 '23 09:02

Yussef


1 2 3 will be the output.

not 4 because the exception is caught in the method's try-catch block

like image 28
Václav Struhár Avatar answered Feb 07 '23 08:02

Václav Struhár