Node.JS
Node.JS

Reputation: 1570

java catching exceptions

    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 ?

Upvotes: 0

Views: 86

Answers (5)

Debobroto Das
Debobroto Das

Reputation: 862

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() ;
    }

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

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();
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

You need to use the new keyword:

throw new InputMismatchException();

Upvotes: 4

evanmcdonnal
evanmcdonnal

Reputation: 48076

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();
    }

Upvotes: 0

awolfe91
awolfe91

Reputation: 1647

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!

Upvotes: 1

Related Questions