Chaps, today I was reading about exception handling and although the book explains them in sufficient details there is something that I really struggle to understand. Ok, here's the example they analyze:

// Fig. 11.2: DivideByZeroWithExceptionHandling.java
// Handling ArithmeticExceptions and InputMismatchExceptions.
import java.util.InputMismatchException;
import java.util.Scanner;

public class DivideByZeroWithExceptionHandling
{
   // demonstrates throwing an exception when a divide-by-zero occurs
   public static int quotient( int numerator, int denominator )
      throws ArithmeticException
   {
      return numerator / denominator; // possible division by zero
   } // end method quotient

   public static void main( String[] args )
   {
      Scanner scanner = new Scanner( System.in ); // scanner for input
      boolean continueLoop = true; // determines if more input is needed

      do
      {
         try // read two numbers and calculate quotient
         {
            System.out.print( "Please enter an integer numerator: " );
            int numerator = scanner.nextInt();
            System.out.print( "Please enter an integer denominator: " );
            int denominator = scanner.nextInt();

            int result = quotient( numerator, denominator );
            System.out.printf( "\nResult: %d / %d = %d\n", numerator,
               denominator, result );
            continueLoop = false; // input successful; end looping
         } // end try
         catch ( InputMismatchException inputMismatchException )
         {
            System.err.printf( "\nException: %s\n",
               inputMismatchException );
            scanner.nextLine(); // discard input so user can try again
            System.out.println(
               "You must enter integers. Please try again.\n" );
         } // end catch
         catch ( ArithmeticException arithmeticException )
         {
            System.err.printf( "\nException: %s\n", arithmeticException );
            System.out.println(
               "Zero is an invalid denominator. Please try again.\n" );
         } // end catch
      } while ( continueLoop ); // end do...while
   } // end main
} // end class DivideByZeroWithExceptionHandling

So, my question is with the throw clause: in line 10 the method quotient throws an exception that will be caught by the catch statement.
SO I wonder, why does that method throws an exception and instead none of these nextInt()

System.out.print( "Please enter an integer numerator: " );
            int numerator = scanner.nextInt();
            System.out.print( "Please enter an integer denominator: " );
            int denominator = scanner.nextInt();

do? Shouldn't they throw an inputMismatchException the same way quotient() throws its ArithmeticException? Or, if you prefer, we can turn things around:
can we get rid of the throws ArithmeticException? So in my head I simply don't understand why one uses a throw clause and the other one doesn't.

thanks iamthwee, I have read that with interest. So if I understand correctly the throw clause is used when it is a method that throws an exception (in the code posted only the quotient method has a throw clause), but then again, nextInt() is a method too and it doesn't have a throw clause: is that because it is inside a try block? Also my understanding was that to catch an exception, it had to be thrown by something, hence the throw clause, but again, as said before not everything seems to be having this throw clause...so although your link provided some interesting insights I am still a bit confused...

Member Avatar for iamthwee

No idea, I'll let the java gurus explain. I'd be guessing at best.

The try-catch statement is a way of handling errors in your program. the throws causes an error to pop up. Like in the example if you have a method called divide, then you would need some error to indicate if the user is dividing by zero. Then the user could andle this error in a try-catch with something like "You divided by 0! Please enter the denominator again", and then this would allow the user to correct their mistake.

So in short the throws keyword creates an error, and the try-catch statement can allow for rectification of the error.

As for your question in the OP. When you use nextInt() and someone enters a text, then the scanner class will throw an InputMismatchException, and then the creator of this program is handling the error with his try-catch. The same thing goes for the arithmeticException exception. When it is thrown by the method, the user handles it.

I hope this clarifies.

Firstly, read this: checked v/s unchecked exceptions

in line 10 the method quotient throws an exception that will be caught by the catch statement

Wrong phrasing; there is a possibility that the method quotient might throw an exception. When a method has a throws clause, it means that the method might throw that particular exception (you can have multiple exceptions but you get the point). The most confusing part with exceptions is that when you are dealing wiht unchecked exceptions (i.e. exceptions which extend the RuntimeException class), you are free to omit the throws declaration when defining methods. But, the important point is that the method can still throw an exception. As an example:

public int intDivide(int a, int b) {
  return a / b;
}

public int intDivide(int a, int b) throws ArithmeticException {
  return a / b;
}

Take a look at the methods defined above; what difference do you see? The only difference is that the second method explicitly mentions/states/informs the method consumer/user that intDivide can throw an exception. Notice that all this is orthogonal to the fact that both of them will throw an exception when passed b=0. It's just that the second method mentions it explicitly but the first one doesn't. Why is this possible? Because ArithmeticException is an uncheked exception.

Now let's consider the example of a checked exceptions:

// invalid
public int readFromFile(InputStream in) {
  return in.read();
}

// valid; works
public int readFromFile(InputStream in) throws IOException {
  return in.read();
}

// valid; works since we *handle* the exception
public int readFromFile(InputStream in) {
  int val;
  try {
      val = in.read();
  } catch(IOException e) {
      val = -1;
  }
  return val;
}

The two methods defined above look very much similar to the example I posted above. But the difference here is that the first readFromFile method won't compile. Why? Because read method of the InputStream class throws IOException which is a checked exception. With methods that throw checked exceptions, the caller should either handle the exception (i.e. use the try...catch block as shown in the third readFromFile method) or propagate it up the call stack (i.e. have throws in the method definition, as we have done in the second readFromFile method).

SO I wonder, why does that method throws an exception and instead none of these nextInt() do

But the nextInt method does mention that it can throw exceptions as you can see from the Javadoc [look at the throws section]. It's just that since you don't have the source code for this particular method in your file, you don't realize that it does mention that it will throw an InputMismatchException in case of a bad input.

Hope that clears things up a bit.

commented: solid +14

Hi all, thanks for your explanations. @~s.o.s~: yes I knew already about the differentce between checked and unchecked (I read about yesterday funnily enough in my book and in the link provided by iamthwee : - )).

The only difference is that the second method explicitly mentions/states/informs the method consumer/user that intDivide can throw an exception.Because ArithmeticException is an uncheked exception.

Yes this is really good to know and clears things up quite a bit already.
Back to nextInt(): I had a look at the link you have provided.
So I appreciate the nextInt() can throw 3 different exceptions and I infer that because of that (and also bearing in mind that it is an unchecked method) we don't need to use an explicit throw clause?. I wonder though, what would happen if we add a throw clause to the nextInt() even if it already throws an exception? Would it work the same way as for the intDivide() method in your code or will it produce an error?

Beware of confusing your terminology here...
methods can not be "unchecked", only Exceptions can be. If you drill further into the JavaDoc you will see that all three exceptions that nextInt may throw extend RuntimeException and are therefore unchecked. The definition of nextInt() in the API source code does not have a "throws" clause; the three exceptions it can throw are just documented in the JavaDoc to be helpful.
There seems to be nothing preventing you from declaring a method as throws <some unchecked exception>, but it's not clear to me what that achieves for you.

Also: "throw" is the statement that you use to send an Exception; you are referring to the "throws" clause in a method signature that lets you know that method may throw a checked exception which you will have to deal with somehow.

thanks, yes sorry I meant "unchecked exception" and not "method". When I say the "throw clause" I mean something like

public int intDivide(int a, int b) throws ArithmeticException {
  return a / b;
}

but I appreciate that there might be some confusion with the terminology from my part, sorry for that.
When I wondered whether nextInt() could have a throw (clause?) I did so only so that I could have the whole exception thing clear in my head, and be able to say something like "Oh ok, so nextInt() can't have a throw clause the same way as the intDivide() method can". But I seem to understand that this is in the method signature (providing it is not a custom defined one).

When I say the "throw clause" I mean something like

Don't call it "throw", call it "throws" clause. You use throw when you want to throw a new exception i.e. create an actual exception object. Something like:

public void transfer() throws TransferFailedException { // this is the *throws* clause
    if(account1.transferTo(account2).hasFailed()) {
      throw new TransferFailedException(); // this is the *throw* clause
    }
}

and be able to say something like "Oh ok, so nextInt() can't have a throw clause the same way as the intDivide() method can"

Generally speaking, the possible exceptions thrown by a method are documented in the Javadoc. If it's not in the Javadoc, you have no easy way of knowing all the possible exceptions a given method can throw except for diving deep into the source code. For e.g. a lot of standard library methods can throw a NullPointerException if presented with a null input but don't mention it in the Javadocs like Pattern.compile.

So to conclude, just hop over to the Javadocs for finding exception related information for a given method or use an IDE which provides all the details. If a method throws a "checked exception", the compiler will anyways warn you (by asking you to either handle it or propagate it up the call-stack).

Ok I see, well that's clear now, at least in theory, will see if I can apply that in practice : -)!
Thanks for your help, and yes now I can clearly see the distinction between the throws clause and the throw clause, sorry for the confusion.
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.