I'm looking to implement my own set of Exceptions
for a projects I am currently working on. The project relies on a core framework with a base framework exception MyFrameworkException
(I am also writing this framework).
For any given project I would like to throw several different types of Exceptions
and I can't decide between using multiple subclasses or a single subclass with some form of an Enum
as a constructor parameter.
In both cases I have:
public class MyFrameworkException extends Exception { /*...*/ }
Option 1:
public class MyProjectBaseException extends MyFrameworkException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
Then, throughout the project I would throw the specific exception for any problem that occurs.
Option 2:
public class MyProjectException extends MyFrameworkException {
public static enum Type {
SpecificType1, SpecificType2, SpecificType3
}
public MyProjectException( Type type ) { /*...*/ }
}
Here I would always throw MyProjectException
with the specific enum type for any problem that occurs. I'd provide some mechanism so that a switch statement could be performed on any MyProjectException
based on the type enum.
What's the best way to handle exceptions in projects, especially those sharing a common infrastructure? Are the two options above good solutions? Why or why not? And what are any better solutions?