I have been searching a lot on when exactly we should go creating custom exceptions. I found this example:
public class IncorrectFileExtensionException extends Exception { public IncorrectFileExtensionException () { } public IncorrectFileExtensionException (String message) { super (message); } public IncorrectFileExtensionException (Throwable cause) { super (cause); } public IncorrectFileExtensionException (String message, Throwable cause) { super (message, cause); } }What's the real value in providing the above custom exception? Instead of creating the above custom exception, why can I not throw a new RuntimeException("error occurred", e)? I have seen many examples on the internet creating similar custom exceptions, but I don't understand what the real benefit in the above approach is.
If we create something like
IncorrectFileExtensionException, then our project ends up with many custom exceptions.I also found this:
public class MyUncheckedBusinessException extends RuntimeException { private static final long serialVersionUID = -8460356990632230194L; private final ErrorCode code; public MyUncheckedBusinessException(ErrorCode code) { super(); this.code = code; } public MyUncheckedBusinessException(String message, Throwable cause, ErrorCode code) { super(message, cause); this.code = code; } public MyUncheckedBusinessException(String message, ErrorCode code) { super(message); this.code = code; } public MyUncheckedBusinessException(Throwable cause, ErrorCode code) { super(cause); this.code = code; } public ErrorCode getCode() { return this.code; } }This is to some extent better than
IncorrectFileExtensionException, as we are providing some error code at least. But again, what if all custom exceptions ends up like the above (I mean with an error code)?My question is: What's the best practice for custom exceptions? When exactly should we go for custom exceptions? Is
IncorrectFileExtensionExceptionreally a good approach?When should we NOT create custom exceptions?