• 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

IOException

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

Hi,

I'm currently in the Exceptions section (of my java course) and my program below relates to the same.

About the program:

To take input from the user a number (integer), check whether its prime number or not and display the appropriate message to standard output.


Issue faced:

The exception thrown is IOException and the catch block should handle the same. However, the IDE (netbeans 6.0) does not allow this
and highlights with the message exception java.io.IOException is never thrown in body of corresponding try statement. When i modified the catch statement by passing Exception class, IDE allows this. At run-time, when i input a string (say java) instead of a number, the error shown is Exception in thread "main" java.util.InputMismatchException (if the catch handler is modified to Exception).

My questions:

1. Why does the IDE not allow IOException to be caught where its thrown and

2. once modified to Exception, the exception raised is java.util.InputMismatchException and not java.io.IOException. Why?

I also modified the below program wherein the PrimeNum class with the method getPrimeNum throws the IOException and this is caught by the TestPrimeNum class. The exception raised (on input of string) again is Exception in thread "main" java.util.InputMismatchException instead of java.io.IOException.


Could any of the expert(s) please explain this.

thanks,
Sudhir

Original code:
----------------





Modified code:
-----------------

 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From the javadocs

IOException signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations



This exception is thrown only when the code fails to read/write data. A string instead of an int (like in your code) would throw InputMismatchException because there is an obvious mismatch - it expects an int but the input was a String.
 
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. Mentioning throws IOException in method signature does not bind us to catch that same exception within method.

2. IOException is never thrown in body of corresponding try statement error is coming because there is no code within try block which throw IOException.
IDE gives error because when we save (Ctrl+S) any java file in IDE(Eclipse,Netbeans etc), IDE complies that java file for us (means ruuning javac command for us).
I hope you have covered Checked and Unchecked Exceptions topic in your course/training.
IOException is an checked exception which means code is checked during compile time for any piece of code which throws IOException and whether it is properly handled or not. We can either catch a checked exception using catch block OR add a throws clause in method signature.
Now coming to your code, you have added a catch clause for IOException but code within try block do not throw IOException.
To remove this exception, i am just adding a throw clause deliberately in your code. When this is added(as shown in code below) , IDE will not give error.
Reason - we have now deliberately thrown IOException in try block which has been properly handled in catch(IOException) block.

So bottom line is - we are not required to catch IOException until unless it is thrown from code present within try block.



3. Reason we are getting InputMismatchException -- nextInt() method of Scanner class throws InputMismatchException if input mismatch happens. So if String is passed instead of int, this method throw this exception.

~ abhay
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sudhir Srinivasan wrote:1. Why does the IDE not allow IOException to be caught where its thrown


When any method / constructor inside the try block can throw an IOException, you'll be able to catch it. But nothing in your try block will ever throw an IOException, therefore you cannot catch it.

2. once modified to Exception, the exception raised is java.util.InputMismatchException and not java.io.IOException. Why?


Because that's the exception that's actually being thrown. InputMismatchException is an indirect sub class of RuntimeException. That means that methods / constructors do not need to explicitly include it in a throws clause. And because it's a RuntimeException, it's also an Exception. That's why you'll always be able to catch Exception.
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sridhar Santhanakrishnan wrote:. . . A string instead of an int (like in your code) would throw InputMismatchException because there is an obvious mismatch - it expects an int but the input was a String.

Not quite. It receives a String but the String must match an int. You cannot pass 123 to a Scanner. But you can pass "123" which is a String-OK for nextInt(). If, however, you pass "Campbell" or "123.45" or "9999999999999999999999999999" which are all invalid for conversion to an int, you will suffer an InputMismatchException.
 
Sudhir Srinivasan
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Thank you Abhay, Rob and Campbell......certainly have more clarity now on the InputMismatchException Vs IOException tangle.


From Rob's and Campbell's responses - Irrespective of the IOException being thrown from within the present code of the try block and handled by the following catch OR thrown and caught elsewhere, the exception raised would always be InputMismatchException when user inputs "java" or "sudhir" etc. [as they are not string representation of int]

Abhay, your detailed explanation of IDE error


IOException is never thrown in body of corresponding try statement error is coming because there is no code within try block which throw IOException.
IDE gives error because when we save (Ctrl+S) any java file in IDE(Eclipse,Netbeans etc), IDE complies that java file for us (means ruuning javac command for us).
I hope you have covered Checked and Unchecked Exceptions topic in your course/training.
IOException is an checked exception which means code is checked during compile time for any piece of code which throws IOException and whether it is properly handled or not. We can either catch a checked exception using catch block OR add a throws clause in method signature.
Now coming to your code, you have added a catch clause for IOException but code within try block do not throw IOException.
To remove this exception, i am just adding a throw clause deliberately in your code. When this is added(as shown in code below) , IDE will not give error.
Reason - we have now deliberately thrown IOException in try block which has been properly handled in catch(IOException) block.

So bottom line is - we are not required to catch IOException until unless it is thrown from code present within try block.



has helped in resolving the same. However, the exception raised would still conform to the other responders explanations.

many thanks,
Sudhir
 
Campbell Ritchie
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you use a Scanner, it consumes any IOExceptions, but there is a method in Scanner which allows you to retrieve its most recent IOException; I think it is called ioException. You can call that method on a Scanner and thorw that Exception (but make sure to use a null test because the throw keyword doesn't react well to nulls ).
You can also find that the nextXXX methods of Scanner throw the InputMismatchException, if you go through the API (scroll up and down from the earlier link). If you look up InputMismatchException, you find it is because the input was not in the correct format. Also (Rob told me how to do this), if you go into the InputMismatchException API page and click on Use at the top, it tells you that thsi Exception is only thrown by Scanner. At least it used to the page isn't working any more. But the API does say "thrown by a Scanner".

You do realise that an IOException is completely different? It might be caused by trying to write to a read-only File, or a loose wire, or some network problem, so you are not getting input or output. You might suffer one of its subclasses instead. If you get an InputMismatchException, you have got some input, but the wrong format.
 
Campbell Ritchie
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sudhir Srinivasan wrote:
Thank you Abhay, Rob and Campbell.....

You're welcome
 
Sudhir Srinivasan
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
You do realise that an IOException is completely different? It might be caused by trying to write to a read-only File, or a loose wire, or some network problem, so you are not getting input or output. You might suffer one of its subclasses instead. If you get an InputMismatchException, you have got some input, but the wrong format.



I've now completely understood that IOException occurs when the code is unable to perform the read/write operations at runtime whereas an InputMismatchException is thrown up when the data input is read but is not the type what the Scanner class expects (in my case, string instead of int).


As per your suggestion


If you use a Scanner, it consumes any IOExceptions, but there is a method in Scanner which allows you to retrieve its most recent IOException; I think it is called ioException. You can call that method on a Scanner and thorw that Exception (but make sure to use a null test because the throw keyword doesn't react well to nulls ).



i modified my code further as


On line 10 i've written the InputStreamReader class with the scan object reference providing the wrap-around for the same in the next line. Lines 29 and 30 invoke the ioException() of the Scanner and throws the IOException. On program execution:

[output]
init:
deps-jar:
compile-single:
run-single:
Enter a number(0 to exit):
12
You have input: 12
Number input 12 is not a prime

Enter a number(0 to exit):
3
You have input: 3
Number input 3 is a prime

Enter a number(0 to exit):
8
You have input: 8
Number input 8 is not a prime

Enter a number(0 to exit):
0
java.io.IOException
null
at PrimeNum.getPrimeNum(PrimeNum.java:37)
at TestPrimeNum.main(TestPrimeNum.java:8)
BUILD SUCCESSFUL (total time: 15 seconds)
[/output]

returns the IOException thrown for the last input(zero) by the Scanner's underlying readable, InputStreamReader. null indicates no such exception exists in this case.

once again, thanks for the inputs and javadocs reference(s).
Sudhir



 
Campbell Ritchie
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why on earth are you throwing a new IOException? That is not what the ioException method is for. You check whether it is null, and if it isn't, you can throw it. You don't want a diffrent Exception.

And never say == true or == false. Write if (flag) ... or if (!flag) ... Not only is that poor style, but also error-prone because you might write = by mistake.
 
Sudhir Srinivasan
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Why on earth are you throwing a new IOException? That is not what the ioException method is for. You check whether it is null, and if it isn't, you can throw it. You don't want a diffrent Exception.



Oops.....sorry about that! Yes, the "throw new IOException" statement is not required when the ioException method of IOException is invoked.

Campbell Ritchie wrote:And never say == true or == false. Write if (flag) ... or if (!flag) ... Not only is that poor style, but also error-prone because you might write = by mistake.



As suggested, i'll certainly conform to the if(flag) boolean expression within the if statement rather than if(flag == true) though i'm clear in the distinction between = (assignment operator) and == (equals operator).

Continuing on the subject of IOException:

java.lang.Object
extended byjava.lang.Throwable
extended byjava.lang.Exception
extended byjava.io.IOException


a) Why does IOException [subclass of Exception class] form part of the java.io package and not of the language package to which the Exception class belongs to?

b) are there any other IOExceptions besides EOFException, FileNotFoundException?

thanks and regards,
Sudhir

 
Rancher
Posts: 3742
16
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sudhir Srinivasan wrote:i'm clear in the distinction between = (assignment operator) and == (equals operator).


You may be but are your fingers ? It's very easy to accidentally type = instead of ==. Doing it how Campbell suggest removes this possibility.

Sudhir Srinivasan wrote:are there any other IOExceptions besides EOFException, FileNotFoundException?


Notice in your post (and this one) that the word IOException has been turned into a link. Click on the link and you will get the answer to your question.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic