priorityqueu example issue

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class PriorityQueue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		java.util.PriorityQueue<String> boy=new java.util.PriorityQueue<String>();
		java.util.PriorityQueue<String> girl=new java.util.PriorityQueue<String>();
        String line=null;
        String file="C\\gpmy\\test.txt";
        String sex="";
        BufferedReader input;
        
        try {
			input=new BufferedReader(new FileReader(file));
			while ((line=input.readLine()) != null) {
				sex=line.substring(0,1);
				boy.add(line.substring(2));
				
			}
		} catch (FileNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        
	}

}

Open in new window


i wonder why above program giving compilation error esp with exceptions.
please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
A FileNotFoundException already is an IOException
0
gurpsbassiCommented:
Look at the API documentation. You will see FileNotFoundException is a subclass of IOException.

You could turn you catch block into something like:
catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

Open in new window


Or if you genuinely want to have different handling for the two exceptions then split into multiple catches:
catch (FileNotFoundException fnfe) {
			// TODO Auto-generated catch block
			fnfe.printStackTrace();
		}
catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		}

Open in new window

0
gudii9Author Commented:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class PriorityQueue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		java.util.PriorityQueue<String> boy=new java.util.PriorityQueue<String>();
		java.util.PriorityQueue<String> girl=new java.util.PriorityQueue<String>();
        String line=null;
        String file="C\\gpmy\\test.txt";
        String sex="";
        BufferedReader input;
        
        try {
			input=new BufferedReader(new FileReader(file));
			while ((line=input.readLine()) != null) {
				sex=line.substring(0,1);
				boy.add(line.substring(2));
				
			}
		} catch (FileNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        
	}

}




How writing below

} catch (FileNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


different from


catch (FileNotFoundException fnfe) {
			// TODO Auto-generated catch block
			fnfe.printStackTrace();
		}
catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		}

I thought we have | which is like or operator right. Writing one below other is like & ie AND operator. please advise

Open in new window

0
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

gurpsbassiCommented:
Yes it acts as a 'OR' but using the multi catch syntax you cannot have multiple exceptions from the same class hierarchy in the catch. That is one of the rules of the JDK 7+ compiler.

e.g. catch(FileNotFoundException fnfe|IOException ioe) is not allowed since both Exceptions are from the same class hierarchy. FileNotFoundException is a subclass of IOException.

catch(FileNotFoundException fnfe | Exception e) is also not allowed either since FileNotFoundException 'is-a' Exception.
0
gudii9Author Commented:
Yes it acts as a 'OR' but using the multi catch syntax you cannot have multiple exceptions from the same class hierarchy in the catch. That is one of the rules of the JDK 7+ compiler.

It looks bit odd. is the rule different before jdk 7?

please advise
0
gudii9Author Commented:
'is-a' Exception.

'is-a' rule is only specific to exception or common across the board(which i do not think). please advise
0
gurpsbassiCommented:
It looks bit odd. is the rule different before jdk 7?
Multi catch did not exist before JDK7.

'is-a' is a term used to describe the relationship when there is a genspec relation (generisation - specification).
Read further on Here
0
gudii9Author Commented:
before jdk 7 we should be able to write one catch and below that other catch(even though below catch is subclass of above catch) .

Please advise
0
gurpsbassiCommented:
before jdk 7 we should be able to write one catch and below that other catch(even though below catch is subclass of above catch

And you can still do that now.

What you are failing to understand is that in JDK 7 multi catch syntax was introduced. This is not a replacement for multiple catch blocks that need to be handled separately. The limitation of multi catch is that you cannot declare exceptions of the same hierarchy in it.

There is nothing to stop you from writing multiple catch blocks in code that is JDK 7 and above. It is still valid. The multicatch is just a tidy way writing your catch statement where the exceptions need to be handled in the same way.
0
gudii9Author Commented:
The multicatch is just a tidy way writing your catch statement where the exceptions need to be handled in the same way.

what you mean by same way. please advise.

Now i am more clear on multiple catch and multi catch.


One thing not clear is

as below link says

http://www.javatpoint.com/multiple-catch-block-in-java

Rule: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

class TestMultipleCatchBlock1{  
  public static void main(String args[]){  
   try{  
    int a[]=new int[5];  
    a[5]=30/0;  
   }  
      catch(Exception e){System.out.println("common task completed");}  
   catch(ArithmeticException e){System.out.println("task1 is completed");}  
   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
   System.out.println("rest of the code...");  
   
 }  
}  

Open in new window


i thought above code is not going most specific to most general but other way (most general exception to most specific arthimaticException)

Please advise

If i were to write above as multi catch code below.


class TestMultipleCatchBlock1{  
  public static void main(String args[]){  
   try{  
    int a[]=new int[5];  
    a[5]=30/0;  
   }  


  catch(Exception | ArithmeticException  | ArrayIndexOutOfBoundsException  e){e.printStack("some exception caught")System.out.println("common task completed");}  
 }  
}  

Open in new window


Above throws error by eclipse forcing me to remove later 2 as they are subclasses of exception class

class TestMultipleCatchBlock1{  
  public static void main(String args[]){  
   try{  
    int a[]=new int[5];  
    a[5]=30/0;  
   }  


  catch(Exception  e){
	  e.printStackTrace();
	  System.out.println("common task completed");}  
 }  
} 

Open in new window



Above code is happy to compiler
0
gudii9Author Commented:
when i run i got below message


java.lang.ArithmeticException: divide by zero
      at TestMultipleCatchBlock1.main(TestMultipleCatchBlock1.java:5)
common task completed

But i wonder how i can handle if i have possibility of different exceptions like arthimetic and array index out of bound both same time in above. How to send different exception message to the user when each happens in multiple catch and multi catch scenario. please advise
0
gudii9Author Commented:
http://www.javatpoint.com/opr/test.jsp?filename=TestMultipleCatchBlock1

when i compile and ran in above link iteself shows below message

java.io.IOException: No such file or directory

which seems incorrect to me.

Please advisee
Exception.jpg
0
gurpsbassiCommented:
you are getting a java.io.IOException: No such file or directory
because your code does not compile.

When using sites such as javatpoint.com to share code snippets it is a good idea to ensure your code compiles first in your local environment first.

The reason it doesn't compile is because the java compiler knows that ArrayIndexOutOfBoundsException and ArithmeticException will never be caught. This is unreachable code so the compiler complains.

Why do you think it cannot be reached? .....hint...it all comes back to class hierarchy. They are both subclasses of exception. Please read the java docs.

I get the feeling that you are missing the core OO principles in your understanding. I would advise reading up on Object Oriented design fundamentals before tackling java.
0
gudii9Author Commented:
class TestMultipleCatchBlock1{
  public static void main(String args[]){
   try{
    int a[]=new int[5];
    a[5]=30/0;
   }

   catch(ArithmeticException e){System.out.println("task1 is completed");}
   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   
   
  // catch(Exception e){System.out.println("common task completed");}
   
   System.out.println("rest of the code...");
 }
}

Open in new window


when i removed that superclass line compiler is happy as above.

class TestMultipleCatchBlock1{
  public static void main(String args[]){
   try{
    int a[]=new int[5];
    a[5]=30/0;
   }

   catch(ArithmeticException e){System.out.println("task1 is completed");}
   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   
   
  catch(Exception e){System.out.println("common task completed");}
   
   System.out.println("rest of the code...");
 }
}

Open in new window


when i put super class at the bottom then also it is happy
0
gudii9Author Commented:
class TestMultipleCatchBlock1{
  public static void main(String args[]){
   
    int a[]=new int[5];
    a[5]=30/0;
  

  // catch(ArithmeticException e){System.out.println("task1 is completed");}
  // catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   
   
  //catch(Exception e){System.out.println("common task completed");}
   
   //System.out.println("rest of the code...");
 }
}

As above if i have code two lines of code,  i selected those two lines which could throw exception.

I right clicked and selected eclipse option of surround by try catch block as attached.


I see it put oas below
[code]class TestMultipleCatchBlock1{
  public static void main(String args[]){
   
    try {
		int a[] = new int[5];
		a[5] = 30 / 0;
	} catch (Exception e) {
		// TODO: handle exception
	}
  

  // catch(ArithmeticException e){System.out.println("task1 is completed");}
  // catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   
   
  //catch(Exception e){System.out.println("common task completed");}
   
   //System.out.println("rest of the code...");
 }
}

Open in new window


It put super exception class only.

How to tell eclipse to put sub cclass specific exceptions like below.
  catch(ArithmeticException e){System.out.println("task1 is completed");}
  catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
please advise
catch.jpg
0
gurpsbassiCommented:
i dont understand your question.
0
gudii9Author Commented:
It put super exception class only as below highlighted

class TestMultipleCatchBlock1{
  public static void main(String args[]){
   
    try {
            int a[] = new int[5];
            a[5] = 30 / 0;
      } catch (Exception e) {
            // TODO: handle exception
      }

 

  // catch(ArithmeticException e){System.out.println("task1 is completed");}
  // catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   
   
  //catch(Exception e){System.out.println("common task completed");}
   
   //System.out.println("rest of the code...");
 }
}


How to tell eclipse to put sub cclass specific exceptions like below.
 
class TestMultipleCatchBlock1{
  public static void main(String args[]){
   
    try {
		int a[] = new int[5];
		a[5] = 30 / 0;
	} 
  

[b]   catch(ArithmeticException e){System.out.println("task1 is completed");}
  catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}[/b]
   
   
  //catch(Exception e){System.out.println("common task completed");}
   
   //System.out.println("rest of the code...");
 }
}

Open in new window

please advise
0
gurpsbassiCommented:
Eclipse won't do that for you.
please read up on the difference between checked and unchecked exceptions. The compiler forces you to catch checked exceptions or rethrow them. With unchecked exceptions like ArithmeticException and ArrayIndexOutOfBoundsException, the compiler does not force you hence eclipse will not generate catch blocks for these exceptions.

Eclipse only generates catch blocks for checked exceptions.
I feel that we have gone off on a tangent to the original topic. If you want to go deeper into eclipse specific behaviour then post a question about eclipse. If you want to discuss more about checked v unchecked exceptions then post another question. This will allow for better traceability.

This question was about the multi catch syntax. Can we close?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
sure
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.