Throwing an exception is one way to get out of a bunch of recursive calls. There are two ways that you can throw an exception: you can reuse an already existing exception, or you can define your own. You might want to look at the handout from class about exceptions.
If there is an existing exception that does the job well, you can throw
one of those. For example, the Scanner.nextLine()
method
already throws a NoSuchElementException
on end-of-file
(which you cause by typing control-D). That doesn't need to be
declared in a throws
clause because it is a subtype of
RuntimeException
.
Remember that you will need to construct a new instance of the
exception class when you throw it. The constructors for the
pre-defined classes will accept a String
parameter as a message.
See here for a partial list of predefined exceptions.
You can create your own class of Exception
and throw
it. If you were to dig out your notes from long ago, you'd find the
following tips:
extends
the existing class Exception
.
String
argument.
super()
to use the
existing exception machinery.
I've included a file SampleException.java
that shows you
how all of this can be done.
Note that throwing your own exception will probably require you to
add a throws
clause to method declarations.