Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Try, Catch, Finally

 
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Once enter the try block, the code in the finally block will be executed with exceptions:
1. an exception arising in the finally block itself
2. the death of the thread
3. the use of System.exit()
4. Turning off the power to the CPU
Let me see if I get this right:
What if there is a finally block. The code enters the try block and an exception is thrown. However, there is no proper matching catch block?
Will the finally block executed? Will the method terminate after the finally block is executed?
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi jiapei,
it is perfectly legal to have a try and finally block without a catch block:
public class ex
{
public static void main(String[] str)
{
try
{
int i=5/0;
System.out.println("try block executed");
}
finally
{
System.out.println("finally block executed");
}
System.out.println("main is executed");
}
}
compiles perfectly but an Arithmetic Exception / by zero is thrown. The code in finally block will be executed and it prints: finally block executed
but the method(and program) will be terminated so none of the statements
System.out.println("main is executed");
System.out.println("try block executed");
will be executed though.
 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for your explanation with an example. It is very clear to me now.
 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sure jaipei,
this is quite obvious but just wanted to add that you cannot have any executable statements between try and finally.
 
reply
    Bookmark Topic Watch Topic
  • New Topic