Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

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
Avatar of ozo
ozo
Flag of United States of America image

A FileNotFoundException already is an IOException
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

Avatar of gudii9

ASKER

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

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.
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

'is-a' Exception.

'is-a' rule is only specific to exception or common across the board(which i do not think). please advise
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
Avatar of gudii9

ASKER

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
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.
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
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.
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

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
i dont understand your question.
Avatar of gudii9

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

sure