I am developing a framework and it can generate various types of exceptions. Initially I'm working with a single exception class that indicates that something went wrong inside the framework. However, I was thinking, maybe it would not be correct to create a specific class for each specific type of exception?

Currently:

There is an unique exception class, which can generate messages like:

  • Framework_Exception: file not found;
  • Framework_Exception: method not found;
  • Framework_Exception: programmer not found;

A possible method more correct

In this case, there should be an exception class for each specific type of error. All of them would inherit the main class (or the class that grouped this type of exception).

  • Framework_FileNotFound_Exception extends Framework_Exception;
  • Framework_MethodNotFound_Exception extends Framework_Exception;
  • Framework_ProgrammerNotFound_Exception extends Framework_Exception;
  • Framework_Method_Exception extends Framework_Exception;
  • Framework_Method_InvalidCall_Exception extends Framework_Method_Exception;
  • Framework_Method_IncorrectParam_Exception extends Framework_Method_Exception;

Which conceptually would be better accepted?

有帮助吗?

解决方案

Using separate exception types for the different types of error that all inherit from a single exception base class is the more useful option for users of your framework.

Using separate exception types has the advantage that users of your framework have the option to implement error handling that is specific for that type of error.

For example, an application could implement a strategy to look for files in multiple different locations based on the Framework_FileNotFound_Exception. And they could instruct the user to call a particular phone number in response to the Framework_ProgrammerNotFound_Exception.
Such different handling is not really possible when all exceptions have the same type.

Inheriting from a common exception type gives your users the additional option to choose to ignore the differences between the error types.

许可以下: CC-BY-SA归因
scroll top