Reputation: 1570
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
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
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
Reputation: 159754
You need to use the new
keyword:
throw new InputMismatchException();
Upvotes: 4
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
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