Try:
throw new Exception("transction: " + transNbr, E);
Answer from Boris Pavlović on Stack OverflowTry:
throw new Exception("transction: " + transNbr, E);
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
Help with throwing custom exception (Homework)
How to Create and Handle a Custom Exception in Java - LambdaTest Community
design patterns - Is it a good practice to use self-defined exception? - Software Engineering Stack Exchange
How do you structure your exception classes?
Videos
I 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)
Like many things in programming, using custom exceptions is good if done for the right reasons and in the right situations.
If a built-in exception can acurrately describe the situation at hand, use it. E.g. FileNotFoundException, TimeoutException, KeyNotFoundException, etc.
If non of the built-in exception classes describe the situation, then you should make your own. If custom exceptions were bad, the built-in classes would be sealed or final or similar. However, don't go nuts. Just like with classes, a given exception type should probably be thrown from more than one place, otherwise it is likely unnecessarily specific.
However, a better rule of the thumb for whether to have custom exceptions is to consider what the caller will do about it when the exception gets thrown. If you have three erroneous situations that are handled in three very different ways, it makes sense to have three types because then the caller can have three catch blocks accordingly. The alternative, which is to inspect the message or data to decide what to do, is more complicated and thus more prone to error.
If all three situations instead are handled identically, it may not be worth the hassle of additional types, when just using the exception message should be enough to diagnose what the situation is. I've had to deal with many situations where a function can throw a dozen different exception types, but that to me as the caller, have inconsequential differences, so laziness kicks in and I just catch {} without the exception type and feel a little guilty about it. Don't cause that to happen.
As for one of the claims you wrote:
catching exceptions is performance hurting.
While that is true, there is virtually no difference between having custom exceptions that are caught and thrown vs just using ApplicationException for everything and making decisions based on the exception message. However, the for former situation, it is considerably easier for us humans to reason about what is happening during program execution.
There's one thing I see in the existing answers that bothers me:
Catching custom exceptions might be code smell.
If you are creating custom exceptions, you shouldn't be catching them. Exceptions are for when things go horribly wrong and recovery is impossible. Exceptions that can be handled are either your own fault or vexing.
Taking from the MSDN article Vexing Exceptions:
I first classify every exception I might catch into one of four buckets which I label fatal, boneheaded, vexing and exogenous.
Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them.
Boneheaded exceptions are your own darn fault, you could have prevented them and therefore they are bugs in your code.
Vexing exceptions are the result of unfortunate design decisions.
And finally, exogenous exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic.
I recommend reading the whole post.
Any design that creates vexing exceptions is a bad design. You (and anyone else writing code against your api) has to catch them, and doing so is vexing: so avoid creating new vexing exceptions.
Custom exception types should either be exogenous ("I'm sorry, Dave, but the database went offline")--and most of these kinds of exceptions have already been written--or Fatal and you should never handle fatal exceptions.
This last point is not adequately presented in the other answers. A bad credit card number is a validation error not an exception. Errors are communicated to the user because they can fix it. Exceptions are things the user can never do anything about. Exogenous exceptions are the exception here, as they are the fault of the world at large and the user needs to be aware of them, even if they can't fix it (but sometimes they can: Internet is disabled, the disk was ejected, the information was wrong. Regardless, there is nothing you as the developer can do to fix it: catch, display, don't crash).
A FamilyNameException is boneheaded: your code had a bug in it. Do not create boneheaded exceptions, do not handle them, write your code correctly in the first place so that these do not occur. Custom exception types are inappropriate for this reason.
A LoginException is either exogenous (the database is offline) or PEBKAC. If it is a PEBKAC error, it isn't an exception. If it is exogenous, why is the existing exception type not sufficient? There may be cases where custom exception types are relevant, but be sure to communicate properly! For example I wrote some code that communicated with an external service, which took time. My coworker was trying to ask my code for the results before the request had time to return, so my code had to generate an exception. However, he took this exception (which was boneheaded in nature) and treated it like a vexing: caught the error and assumed all zeros, thereby introducing a bug: the data retrieved from the external service was wrong! (No, the data was right, but he wasn't displaying the retrieved data and blamed my code). I ended up having to fix his code twice (he removed my first fix about 2 weeks after I added it).
To sum up:
- Catching any fatal or boneheaded exception is code smell.
- A custom vexing exception class is code smell. See also: How to avoid vexing exceptions.
- Be careful with custom exogenous exceptions: they are either redundant or can be mistaken for vexing exceptions.