Skip to main content

Why it is mandatory to use "throws IOException”



Why it is mandatory to use "throws IOException" in main method while handling an external file operation, if the file is located within the local file system.




Comments

  1. It is not at all mandatory to use throws IOException. If you call a method that can throw an exception, though, you're required to either


    Catch it, or
    Declare that you're going to rethrow it.


    The second one is what you're doing. The other one -- which is often the preferred technique -- is to catch and handle the exception yourself:

    public static void main(String[] argv) {
    try {
    FileReader f = new FileReader("foo.txt");
    // ... more
    } catch (IOException ioe) {
    System.out.println("Trouble reading from the file: " + ioe.getMessage());
    }
    }

    ReplyDelete
  2. AFAIK, it is not mandatory.

    You either handle the exception or you don't.

    If you do handle the exception, then you need to put a try {...} catch(IOException e) {...}, but if you don't handle it, just declare the throws IOException in the current method.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...