Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


For this main method,don�t we need to declare the Exception,since priya() method throws it.I compiled this program with declared FileNotFoundException as well as without it.Both are running fine.But I didn�t get it.Please help me.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You throw a FileNotFoundException exception and you catch it in your priya() method.

If you have a "throws FileNotFoundException" clause at priya() method declaration then you need to catch it in main method, otherwise a compile-time error.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.In the priya() method,we must be caught the exception or declared to be thrown.(here,i caught it instead of throws FileNotFoundException).in the main method,we called priya()method that obviously throws FileNotFoundException.For calling priya() method inside the main method,don't we need to mention

public static void main(String[] args) throws FileNotFoundException{
priya();
}
I hope you have understood my doubt.
 
luo luo
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just tested it, if the exception thrown (using throw) can be caught by the method itself. then the exception won't propagate to the calling method and you don't have to declare it in the throws clause.

Otherwise, you have to throw and declare it and the calling method has to catch or propagate it.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you have a "throws FileNotFoundException" clause at priya() method declaration then you need to catch it in main method, otherwise a compile-time error.


are you trying to say
If you have a "throws FileNotFoundException" clause at priya() method declaration then you need to declare it(public static void main(String[] args)throws FileNotFoundException),otherwise a comapile time error.

if you don't have a "throws FileNotFoundException" clause(instead we caught it)at priya() method declaration then we don't need to declare it in main.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic