Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Queston on exceptions

 
Sandya Bhaskara
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class A{
void method(){
try {
meth();}catch (RuntimeException e){}
catch (Exception e){}
}
}
void meth(){

throw new RuntimeException()
}
}


will this code compile??
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, but that would have been easy enough to test. The following does compile:


Is there a question here you are looking for an answer to?
 
Sandya Bhaskara
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here...meth()doesn't throw any checked exceptions..and method() is catching the only runtime exception that meth() throws..so why doesn't the compiler give an error?- catching an exception(here---catch (Exception e)) that has never been thrown??any exception that isnt a checked exception is a runtime exception...and that is caught by the code..so is it ok to catch Exception again??am i clear?
 
Thana Bujakorn
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my opinion, it should compile just fine.


It doesn't seem to violate any of the exception rules. You must declare that a method "throws" exception or provide a catch clause for it only if it is checked exception. RuntimeException and its subclasses are considered unchecked.
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It won't compile without adding a semicolon the following line:
throw new RuntimeException()

but I don't think that is the answer you were really looking for...
 
Sandya Bhaskara
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nopes..its not the semicolon thing......that was a typo...
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beside the semicolon typo Chris mentioned, there is an extra bracelet on line 6 that should be removed.

The modified code should look like this



You may want to use proper indentation next time in order to make your code more clear and readable, consider also using the [code] tags.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic