• 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

Why not to enclose in try-catch block??

 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here is the program that i tried to compile...

import java.io.*;

class Writer4 {

public static void main(String... args) {

try {

String[] files = new String[50];

File search = new File("newDir");
files = search.list();

for(String fn: files)
System.out.println("Found:: " + fn);
}
catch(IOException e) {
e.printStackTrace();
}
}
}

I got this unusual complier error::

Writer4.java:17: exception java.io.IOException is never thrown in body of corresponding try statement
catch(IOException e) {

but if i remove the try-catch block it complies fine!!!

why there is no need to enclose the code in try-catch block even though we are dealing with files..??

[ June 22, 2007: Message edited by: Priyam Srivastava ]
 
Ranch Hand
Posts: 242
Mac Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because there is no checked exception is being thrown in your code..

And by writing IOException, U are being more specific to checked exception..

You can try by writing Exception instead of IOException..
The code will work fine..
As that will be more generic and include runtime exceptions..

By handling IOException, you are being more specific to unthrown checked exception..
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi priyam

this is because neither list() nor file(String pathName) constructor of File class throws IOException. You can verify this fact from java API.
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since because any of the executable statements inside try block does not seem to throw the exception whose type is being caught in catch block, the compiler gives an error saying that the specific exception is never thrown.

HtH.
 
reply
    Bookmark Topic Watch Topic
  • New Topic