Expand my Community achievements bar.

SOLVED

Define and throw a dedicated exception instead of using a generic one

Avatar

Level 4

what it means

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @vinuu123 

 

You should not throw generic exceptions. You should be subclassing Exception and then throwing your subclass, so that the type of the exception actually provides information about what is going on, allowing clients of the function to catch and treat it appropriately.

 

Example:

Here Exceptio is generic in nature and you should not be using it. Instead of that you should use the specific category type i.e., either "LoginException", "RepositoryException", depending upon the nature of exception. Or you can define your own exception and use here.

 

try {
// Some code
} catch (final Exception e) {
LOG.error("***** :: Exception :: ***** {}", e.getMessage());
}

 

Thanks!

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

Hi @vinuu123 

 

You should not throw generic exceptions. You should be subclassing Exception and then throwing your subclass, so that the type of the exception actually provides information about what is going on, allowing clients of the function to catch and treat it appropriately.

 

Example:

Here Exceptio is generic in nature and you should not be using it. Instead of that you should use the specific category type i.e., either "LoginException", "RepositoryException", depending upon the nature of exception. Or you can define your own exception and use here.

 

try {
// Some code
} catch (final Exception e) {
LOG.error("***** :: Exception :: ***** {}", e.getMessage());
}

 

Thanks!