You should be able to create a custom exception class that extends the Exception class, for example:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
Answer from Rion Williams on Stack OverflowI don't really work with exception handling a lot, so I'm out of my comfort zone for this assignment. In essence, the code I'm testing is a List object, checking it to see if the object I want to add already exists within the list, and throwing a custom exception if it does. I'm using junit testing, if that matters.
public void addConnection(LinkedInUser user) throws LinkedInException
{
try {
for (int x = 0; x < connections.size(); x++)
{
if (connections.get(x) == user)
throw new LinkedInException();
}
//if (connections.contains(user))
// throw new LinkedInException();
//else
connections.add(user);
} catch (LinkedInException e) {
e.Exception("You are already connected with this user");
}
}The commented portion was the old code. I think the problem is determining whether or not the object is already within the list, but I could be wrong. The LinkedInException class is just an empty class. Our instructor told us to override the five Exception class constructors, but that was it, so the overrides are blank.
Here's the junit test code
@Test
public void errorCheckAddCon()
{
LinkedInUser test = new LinkedInUser("han", "password123");
LinkedInUser test1 = new LinkedInUser("luke", "password123");
boolean exceptionThrown = false;
try {
test.addConnection(test1);
test.addConnection(test1);
} catch (LinkedInException e) {
exceptionThrown = true;
}
Assert.assertTrue(exceptionThrown);
}(I think it's the addConnection method, and specifically the List.contains method within, because I manually set boolean exceptionThrown to true, and the junit test passed, so the junit test code isn't the issue here I believe)
How to create a custom exception type in Java? - Stack Overflow
Is it bad practice to throw multiple custom exceptions in Java? - Software Engineering Stack Exchange
java - Throwing custom exceptions in library: do I throw concrete ones or their superclass? - Software Engineering Stack Exchange
How to Create and Handle a Custom Exception in Java - LambdaTest Community
Videos
You should be able to create a custom exception class that extends the Exception class, for example:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
You need to create a class that extends from Exception. It should look like this:
public class MyOwnException extends Exception {
public MyOwnException () {
}
public MyOwnException (String message) {
super (message);
}
public MyOwnException (Throwable cause) {
super (cause);
}
public MyOwnException (String message, Throwable cause) {
super (message, cause);
}
}
Your question does not specify if this new exception should be checked or unchecked.
As you can see here, the two types are different:
Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.
Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException
Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.
Is it bad practice to throw multiple custom exceptions in Java?
No. It is good practice.
The only situation where multiple exceptions might be a (slightly) bad idea is if there is absolutely no possibility (ever!) of catching individual exceptions; i.e. the fine-grained exceptions won't serve any functional purpose. However, my opinion is that if you can make that assertion, then there is probably something wrong with the way that you / your team is using Java. And the counter-argument is that sensible use of multiple custom exceptions will help you to document the APIs ... even if you are never going to do more than catch-log-and-bail-out at runtime.
This is not to say that lots of custom exceptions will always be good:
If you go overboard and create a separate exception for everything, then you are probably adding unnecessary complexity. (In a lot of cases, different exception messages are sufficient.)
If you don't have a sensible inheritance hierarchy for your custom exceptions, then you may end up regretting it. (A well-designed hierarchy allows you to catch "classes" of exceptions, or declare methods as throwing them. It can make your code simpler.)
Is it bad practice to throw multiple custom exceptions in Java?
Generally speaking: No. Why should it?
As with everything: Abstraction is your friend.
Is it necessarry to have a CustomerNotFound Exception and a ProductNotFound Exception? Or are your requirements just a more abstract NotFoundException?
The context could help to determine, what was missing. Having different exceptions for the sake of having them is nonsense.
Is it necessary, each layer of your application having custom exceptions? Exceptions are a way to report, that an intended action failed due to some reason.
Say, you have a controller which asks the service-layer to retrieve data, which in turn asks the DA-layer to read values from the DB. The resultset is empty. The service gets the empty resultset and throws a
NotFoundExceptionthe service communicates, the failure of the action due to a missing result.Say, the controller needs the service to do the payrolls for employees. And the service is asked to do the payroll for the employee with ID
123456, and in turn asks a service to retrieve the employee - but no emloyee could be found.
There are two ways to deal with that:
1) You throw a NotFound exception in the DA-Layer, catch it in the payroll-service and rethrow a PayrollServiceException wrapping the NotFoundException with the message Exmployee could not be found
2) You throw a NotFound exception in the DA-Layer and do not catch it in the payroll service and catch it instead a layer above.
I would go for (2), since in (1) the information, that the action failed because of a missing employee is redundant.
Throwing a generic exception like FooServiceException makes your method signature easy to read, but you're also assuming the caller is not likely going to want to differentiate. If he did, he could still do so, but he'd have to pilfer through your code to find out which specific implementations of FooServiceException are thrown. Don't make the caller do that! That is why we can't have nice things!
On the other hand, if your method getById is throwing FooConnectionTimeoutException, FooConnectionPoolExhaustedException, FooTableNotFoundException, FooServiceObjectNotFoundException, clearly something is not right about this either. But fear no more, my good OP! There is a solution.
You can organize exceptions by type, then throw a reasonably generic exception for each type possible. In other words, have FooConnectionTimeoutException, FooConnectionPoolExhaustedException, FooTableNotFoundException all derive from FooDatabaseException. Your method signature then becomes:
getById(int id) throws FooServiceObjectNotFoundException, FooDatabaseException;
See how nice this is? Callers wanting to cover any and all exceptions would look no further than handling just FooServiceObjectNotFoundException and FooDatabaseException. Callers wanting to perform a different action upon FooServiceObjectNotFoundException can do so no qualms.
You can further organize according to necessity if you want to be more detailed, but the level of detail is entirely up to you. The key point here being that you have full control over how specific you want your exceptions to be. As a general rule, try to reduce the number of exceptions thrown to 3 or less. Anything beyond that is somewhat unnecessary, especially if many of the exceptions are related to the same type of issue (unexpected problems, business errors, invalid input, etc.).
The exception specification is an addendum to the return value, so it should follow similar guidelines.
I would suggest that you use the least specific type that satisfies the needs of the consuming code. In your case that might be FooServiceException, but it's equally plausible that Exception or Throwable is sufficient. You don't detail the members of FooServiceException, so I can't tell.