0
    try {
        if (x.length == Styles.size()) {

        }
        else{
             throws InputMismatchException ;
        }
    } finally {
        OutputFileScanner.close();
    }

I get compile error in method contains code above , is there any way to throw InputMismatchException in else block ?

1
  • It's probably just complaining that you haven't declared that your function is possible of throwing the InputMismatchException. Try adding "throws InputMismatchException" to the end of your function definition. Commented Nov 27, 2012 at 2:30

5 Answers 5

4

You need to use the new keyword:

throw new InputMismatchException();
Sign up to request clarification or add additional context in comments.

2 Comments

All these "declare throws" answers and everything, sheesh, I thought I was going to have to answer this one. InputMismatchException isn't even a checked exception, it's a subclass of RuntimeException. +1
Yep, left the RuntimeException bit out as the OP probably isn't declaring it anyway (or at least shouldnt be).
1

A "throws" declaration doesn't go in the method body. If you want to simply throw the Exception, declare it as follows:

    public void method() throws InputMismatchException{

    if(...) {...
     OutputFileScanner.close();
   }
    else{
      OutputFileScanner.close();
     throw new InputMismatchException("Uh oh");
      }
    }

There's no need to use a try statement here. When you call method(), you will use the following:

try{
  method();
} catch (InputMismatchException ime){
   //do what you want
 }

Hope that helps!

Comments

0

You want to create an instance of the exception then throw it. throws is used as part of a method declaration, not to actually throw the exception.

    if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException();
    }

Comments

0

Declare the method it lives in to throw the exception.

Because OutputStream.close() throws IOException you'll need to throw that too:

void myMethod() throws InputMismatchException, IOException {
    // your code, except 
    throw new InputMismatchException();
}

Comments

0

When you throw exception, then there is no need to try-catch-finally it. try catch finally is necessary when you catch an exception. try the following--

if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException() ;
    }

2 Comments

He needs to close his scanner to keep from having resource leaks, so suggesting that he doesn't need this is completely incorrect.
I was commenting w.r.t. of exception handling. obviously he needs to free the resource. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.