Java Reference
In-Depth Information
abstract Rational parse(String number) throws
When method parse() receives a string representing a number, it is
possible that an error occurs, the reason being the incorrect format of the
string. To handle the possibility of errors in the parse() method we declare
that this method can throw an exception. The reasons and consideration
behind this choice are discussed in Sidebar 6.2.
Since the cause of the error in parsing is very specific we define a new
class that represents this exceptional condition: FormatException . This class
extends the Exception class, which is part of the core Java classes (in package
java.lang ). The only method implemented is the constructor that simply
passes the message string to the superclass's constructor.
public class FormatException extends Exception {
public FormatException(String msg) {
super (msg);
Sidebar 6.2 Error handling
When an error is found in a method there are two possible solutions:
returning an error code, or
throwing an exception.
The first solution is particularly complex when the method has a return value
that represents the result of the execution; in this case a special value of the return
value (e.g. null) is returned to signal the presence of an error.
Let's consider the two solutions in term of the code required to implement
them. In the first case the class that signals the error looks like the following one:
public class C {
Object method(){
/* .. */
if (some_error_condition) return null ;
/* .. */
When using exceptions the code is the following:
public class C {
Object method() throws MyErrorException(){
/* .. */
if (some_error_condition) throw new MyErrorException();
/* .. */
public class MyErrorException extends Exception {
Search WWH ::

Custom Search