try{
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(),input.next(),input.nextDouble());
} catch(FormatterClosedException formatterClosedException){
System.err.println("Error writing to file. Terminating.");
break;
} catch(NoSuchElementException noSuchElementException){
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
The method format(String format, Object... args)
in Formatter
class throws two exception
: IllegalFormatException
and FormatterClosedException
but in my book the above code catches NoSuchElementException
and FormatterClosedException
.
- Why did the code catch
NoSuchElementException
but did not catchIllegalFormatException
? - How can we know if we need to catch
NoSuchElementException
if it is not even stated in the Formatter class format() method in the online documentation ?
add another
catch
withException
class. That is the parent class.You can add
catch
for everyexception
that your code throws and in the end add this catch with this Exception parent class. If yourexception
is not caught by any of thecatch
then this will caught your exception.It will catch all exceptions that is raised by your program.
In your case it is
Scanner
. Its not fromformat
method.It's just to be in the safer side(if next input is not given then throw this exception).
Sample code which shows the demo
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric
String
to a number (NumberFormatException
) or calling a method on anull
reference (NullPointerException
). You can catch them in many ways.or using the fact, that they all extend
Exception
:or since Java 7:
You have to catch all
checked exceptions
. It's due to the language grammar. On the other hand, there areunchecked exceptions
which doesn't necessarily need to be caught.IllegalArgumentException
is unchecked exception and therefor doesn't need to be caught.NoSuchInputException
can be thrown byinput.next()
. That's why it's declared to be caught.So:
Exception
s.input.next()
canthrow NoSuchElementException
format
canthrow FormatterClosedException