• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Try,Catch

 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the below code i had commented catch part.
so i am getting the below error
--------------
D:\prabhu@java>javac MyException1.java
MyException1.java:4: unreported exception BadFoodException; must be caught or declared to be thrown
try{checkFood(args[0]);}
^
1 error
------------
class BadFoodException extends Exception{}
public class MyException1{
public static void main(String[] args){
try{checkFood(args[0]);}
/*catch(BadFoodException e){
e.printStackTrace();
}*/
finally{System.out.println("finally");}
}
static void checkFood(String str) throws BadFoodException{
if (str.equals("nofood")){
throw new BadFoodException();
}
else{
System.out.println("i like it");
}
}
}
-----------------------------
my query:
1.try should have either catch or finally.so if remove catch why the code not working,finally is still there know.
Please clarify.

prabhu
 
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Prabhu,

Use Instant UBB code Code button whenever you paste some code on this forum.It will give better clarity to the reader.

Since your method checkFood throws BadFoodExeption so it is neccessary to the caller method either to throw or catch the exception. Since your method checkFood throws BadFoodException you must catch it in your main method.


Regards
 
m prabhu
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi patricia,
thank you.i got it.
if no exception is thrown by checkfood() then,try & finally will do.

i follow code templates hereafter
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic