• 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

Exceptions

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is it legal having Try block either with catch clause or finally clause.
what happens if we remove catch clause.
then how finally will handle any exception caught.
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Anilkumar,

It is mandatory to have catch or final(or both) with try block. If you dont write catch or final block then compile time exception will be thrown while you compile your program...
final block will always executed not matter if exception will be thrown or not at runtime... Here most of the time you close external resources(like DB connection )...

Do let me know if i can assist you more...

Cheers !!!
Sumit Malik
 
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if you dont have a catch in the try-catch-finally method then your checked exception wont be caught. Hence, it wont be able to compile.

See example 1 where catch block is not there and the expection is not handled at all.

example 1:
class Uncatch
{
public static void main(String[] args)
{
try
{
throw new Exception();
}
finally
{
System.out.println("finally");
}
}
}

In the example above, the code will not get compiled since there checked exception is neither caught nor handled.

now see the second example...

example 2:

class Uncatch
{
public static void main(String[] args) throws Exception
{
try
{
throw new Exception();
}
finally
{
System.out.println("finally");
}
}
}


In the second example, the expection is not caught but handled by throws statement that is why it will compile and when you run it. The output would be ...

finally
Exception in thread "main" java.lang.Exce
at Uncatch.main(Uncatch.java:7)

i.e. the finally statement is executed and then the exception is displayed.

no matter what. Finally is always executed unless the program in a catch or try block has something like System.exit().
 
reply
    Bookmark Topic Watch Topic
  • New Topic