P K
P K

Reputation: 10210

Is there any priority between multiple try/catch execution in java?

In the below program, sometime i get following output:

Number Format Execption For input string: "abc"
123

and sometime:

123
Number Format Execption For input string: "abc"

Is there any priority between try/catch block or priority between System.out and System.err?

What is the reason of random output?

code:

String str1 = "abc";
String str2 = "123";

     try{
         int firstInteger = Integer.parseInt(str1);
         System.out.println(firstInteger);
     }
     catch(NumberFormatException e){
         System.err.println("Number Format Execption " + e.getMessage());
     }

       try{
         int SecondInteger = Integer.parseInt(str2);
         System.out.println(SecondInteger);
         }
     catch(NumberFormatException e){
         System.err.println("Number Format Execption " + e.getMessage());
     }

Upvotes: 3

Views: 306

Answers (2)

cvanes
cvanes

Reputation: 31

Try flushing the streams explicitly,

System.out.flush();
System.err.flush();

Upvotes: 0

Francis Upton IV
Francis Upton IV

Reputation: 19443

It has nothing to do with the try/catch and everything to do with that you are writing to System.out and System.err; they are two different streams and you can't control the order of their interleaving as they are written to the console.

Upvotes: 12

Related Questions