Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Common Catches

 
Nick Delauney
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all,
quick question, If I have two IOExceptions, but I want to differentiate which IO excpetion was thrown so that I could print out two different messages, How would I do that ? Do I have to have a second try ?
try
{
throws IOException // First one
throws IOException // Second one
}catch(IOException ioe)
{
System.out.println(" IO Exception happened, no clue which one");
}
Thanks,
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use two or more catch blocks. Be sure to list the more specific Exceptions first (that is subclasses of the checked Exception). For Example:
 
Nick Delauney
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Morris,
But, I'm wondering how would you differentiate between two of the same exceptions. In other words two IO EXceptions get thrown. How would I do a print statement to say which one?
Keep in mind there just IO Exceptions not anything derived from it but expicitly that type of exception.
How do you differentiate if the same expecption can be thrown two different ways in one try.
[ May 29, 2003: Message edited by: Nick Delauney ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If both exceptions are of type IOException (and noot any subclass), then you would have 1 catch black with an if/else statement inside. The if would have to check some value of the exception.

Although, in general, testing the .getMessage() is proabably a bad idea (it might change over time...)
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But, I'm wondering how would you differentiate between two of the same exceptions.
Well the safest approach would be to seperate the risky I/O statements into their own try blocks. You can also try what Joel posted but as he said, that is not a sure thing.
 
Nick Delauney
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both
 
Rodrigo Dinis
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
You must see the inheritance of your exception class and put the catches in the follow order: subclasses before and superclasses after, ex:
try {
/// IO code
} catch( EOFException e ) {
} catch( FileNotFoundException e ) {
} catch( IOException e ) {
}
Consider that EOFException and FileNotFoundException extends IOException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic