In addition to catching exceptions, Java allows you to generate your own exceptions using the throw statement. The default Exception objects can store a string, indicating an error message. In addition, you may add more structure in a user defined subclass of Exception. If you do not want class LinearList to have negative entries you might write:
class NegativeException extends Exception{
private int error_value; // Stores negative value that
// generated the exception
public NegativeException(String message, int i){ // Constructor
super(message); // Appeal to superclass constructor for message
error_value = i;
}
public int report_error_value(){
return error_value;
}
}
Now, inside LinearList you might write:
class LinearList{
...
public add(int i){
...
if (i < 0){
throw new NegativeException("Negative input",i);
}
...
}
}
Notice that we directly passed the reference returned by new rather than creating a temporary local variable of this type as follows:
public add(int i){
NegativeException ne;
...
if (i < 0){
ne = new NegativeException("Negative input",i);
throw ne;
}
...
}
When another program uses add(i) in a LinearList, it should be aware of the possibility that a NegativeException may be thrown. Java insists that this exception throwing capability be ``advertised'' in the function definition, as follows:
class LinearList{
...
public add(int i) throws NegativeException{
...
}
...
}
Actually, Java relaxes the rule about advertising exceptions so that a program can throw a built in exception of type Error or RunTimeException without advertising it.
We can now use add(i) externally as:
LinearList l = new LinearList();
...
try{
...
l.add(i);
...
}
catch (NegativeException ne){
System.out.print("Negative input supplied was ");
System.out.print(ne.report_error_value);
}
...
As mentioned earlier, Java takes a rather extreme stand in classifying ``non-normal'' execution as an exception. Reaching the end of file throws an IOException, so the normal structure of a read loop from a file in Java would be:
try{
while(...){
... // read from a file
}
}
catch (IOException e){
if (e ... EOF) { ...} // if e indicates EOF
...
}