Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Deriving New Exception Classes

The exception classes can be used as is; that is, they can be used simply to report an error message describing the error that has occurred. However, this is virtually useless as an exception handling technique. Simply knowing what the exception was doesn’t do much to increase software reliability. The real value of the exception class hierarchy is the architectural roadmap provided for the designer and the developer. The Exception classes provide basic error types that the developer can specialize. To demonstrate how to specialize an exception class, let’s use the IOException class as an example. The IOException class is a descendant of the Exception class. We can specialize the IOException class through inheritance, as shown in Listing 3.

Listing 3 robot_io_exception specializing IOException.

class robot_io_exception extends IOException{
boolean no_way;
robot_io_exception()
{
   no_way = false;
}
robot_io_exception(String SomeDefect)
  {
   super(SomeDefect);
}
void robotRecovery()
{
   //special robot recovery instructions
}
}


void someIOProcess()
{

 try{

  //Do some IO processing
  ...
  if(no_way){
  robot_io_exception NotPossible =
  new robot_io_exception("Impossible!");
  throw NotPossible;
  }
  ...
 }
 catch(robot_io_exception SomeFault)
 {

  System.out.println(SomeFault.getMessage());
  SomeFault.robotRecovery();
 }
 finally{
  // Close IO devices
 }
}

In Listing 3, the robot_io_exception is derived from IOException. It adds a robotRecovery() method that implements the exception handling strategy for the robot device. The developer is able to take advantage of the Java exception hierarchy and provide the additional work that the Exception class needs to perform.

  • + Share This
  • 🔖 Save To Your Account