Why should we write custom exception classes in Java - java

What is the purpose of writing custom exception classes when mostly what it does is same.
For eg, NullPointerException:
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
public NullPointerException() {
super();
}
public NullPointerException(String s) {
super(s);
}
}
This is the basic template for most exception classes that I have seen and created.
One purpose I can think of is in handling these exception.But then cant this be based on Exception Message?. Mostly we write single handling code for each exception type. I know there are 'exceptions' to this.
But is there anything more to it? Isnt this repeating yourself where only the class name changes?
Also are there any JDK Exception classes that has some code than this?

I can think of several reasons:
Having multiple exception classes allows the programmer to be specific in their catch clauses, and only catch the exceptions they care about and know what to do with.
An exception class can carry information about the error that's caused the exception. For example, ArrayIndexOutOfBoundsException carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.
Exception specifications -- that list exception classes -- can be used to check correctness at compile time.

Well, simply put, if you do not need special exception class, you should not make one. If you do, then you make one. There's no magic to it really.
If you're making a library, then you should of course think from the point of view of the developers using the library (even if it is just you): does your library throw exceptions for specific reasons and could the library user possibly want to catch specifically these, because they can realistically do something about it (just logging isn't reason enough, IMO).
Example with standard exception classes: Caller of a method might want to convert IndexOutOfBoundsException to null return value, while letting other exceptions to propagate normally.
If you want your custom exception to be handled in default ways, you extend right existing exception class, such as IOException. You can then catch your specific IO exception when you want to do something specific just there, but also let it be handled like any other IOException when you don't need special handling (can't do anything useful to recover).
If you have a totally custom exception which should never be caught by a superclass catch, which always should have specific catch block, then you extend Exception directly.
I think it's pretty rare to need to extend RuntimeException, because if it an exception meant to be caught it should be Exception subclass, and if it's meant to end the program or just generate log output, then it should be covered by default RuntimeException implementations with custom message string.

You need to have your client code know what exact exception happens by which part of code. so you need to let exception semantic and distinguished from other code block.
How to do this:
Define new exception class, so the class name tells what happens
Define a unifed/generic exception class which wraps code, message or other info. the code can tells what happens.
To summarize it, Do something let your exception have some meaning/semantics, and let its client know what exactly happens.

We will have a freedom to add few more methods into our Exception class which helps the client like rootCauseOfException(),description(),solution(),suggestions() etc.
Can refer below link:
https://stackoverflow.com/a/22698673
If your project has interdependent modules then you can maintain exception hierarchy also in the same dependency hierarchy so that if you catch single Exception in base layer then all the interdependent modules exceptions will be caught.
You can also mask some sensitive data like ip ,port etc before sending to client side. If custom exceptions are not used then some sensitive data can may get leaked to slient.
You can provide your own exception message which can be easily understandable by client rather than java's exception message sometimes which may be hard to understand .

It is basically to Handle different Exception in different ways. Say, you might want to do some different operation on ArrayIndexOutOfBoundsException than a NumberFormatException.
or more clearly
}catch (ArrayIndexOutOfBoundsException ex){
//operation 1
}catch (NumberFormatException ex){
//operation 2
}

The main purpose would be identify the custom / app-specific errors. You can also provide some additional methods there. For eg, we have custom exceptions that return custom messages, and also extracts cause and location from the stack trace.

Related

Transforming Exceptions thrown from an external library in a centralized way

I would like to ask a code style question around Java Exceptions. I am using Java to call a C/C++ library using JNI. The convention in the library I am using is that most of the methods I can call will throw the same exception type for all errors. Let's call that a LibException. Now LibException is really a wrapper exception for a multitude of errors that can come up ranging from authentication problems, connection problems or more serious problems like corrupt input etc. LibException also contains an error code int as well as the error description string.
Even more confusingly LibException can also wrap one of my own exceptions if I throw it at the library in a callback! What I mean by that is that I sometimes provide a callback method, it is called by the library and I sometimes have to throw an exception in the callback. In that case the library picks up the exception, wraps it up in a LibException and throws it back at me in the original method call.
I would like each of the underlying problem to be handled differently. Authentication problems need to be shown to the user so he can retry, users should be notified of connection problems, but more serious problems may have to trigger my diagnostics report system (an automated mechanism that can send me parts of the logfile for debugging) and of course any exceptions I throw towards the library in the callback need to be rethrown as the original exception type.
Since I am calling different methods at multiple locations, I thought it would be a good idea to put some structure around the exception handling of LibExceptions. This is to avoid code repetition but most importantly to make sure that the different exception types are handled properly and that future me does not forget to, for example, notify the user that authentication failed.
I have tried a bunch of approaches but I am not entirely happy with the code structure I get so I would like some ideas on best practices from the community.
Static method that includes logic to sort the exceptions and throw a bunch of other exceptions
public static void handleException(LibException e) throws AuthenticationException, ConnectionException, SeriousException, MyException (MyException would be my exception that I throw in the callback)
+ve This works well in that it forces the handling of all the thrown exceptions.
+ve If a new exception type is added, the compiler would force me to handle the new exception
-ve Even though handleException() is a method that always throws an exception, the compiler (rightly) does not know this. This means that if we use handleException() in a method that has to return something, the compiler complains that a return type was missed. To make the compiler happy I have to throw another exception right after calling handleException() so the compiler understands that it will not be getting a return value because an exception is definitely thrown.
-ve I don't like the line that looks like Handler.handleException(libEx) since it's not entirely obvious that it throws a bunch of exceptions.
-ve Hard to customize the exception messages with context from the location the exception occurred (i.e. which URL we could not connect to).
A method that returns an enum with the different types of exceptions that I defined. Based on the enum I can then create the different exceptions to throw.
public static ExceptionTypeEnum Handler.
+ve Since I create the exceptions, I can now customize some error messages with extra context
-ve I could still forget to handle an enum (especially if I create a new category in the future)
-ve I still need a bunch of custom code to create the exceptions at every place I catch a LibException
Similar to #2 but instead of an enum return I could have multiple methods such as isAuthenticationException(libEx) or isConnectionProblem(libEx) and then accordingly throw the exceptions myself.
-ve I would definitely forget to handle all sections properly especially if a new exception type is added later.
The exception handler could return an exception to throw up. But since we throw a number of different exceptions the getException() method would have to return the Exception base class. This means that exception handlers would have to have prior knowledge of what exceptions could be thrown and also catch the Exception class making my exception handling more difficult.
Now in case I confused everyone with this question, I guess what I am trying to find an elegant solution to is similar to the problem described on section 'Checked exceptions inappropriately expose the implementation details' on page http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html
Does the community have any other suggestions of a coding method to properly and elegantly handle these LibExceptions?

How to avoid creating custom exception classes whilst still throwing exceptions at an appropriate level of abstraction?

I'm reviewing my understanding of exception handling (in the context of Java), and trying to figure out what types of exceptions are most appropriate to throw. One comment that I'm regularly seeing is that it is generally better to avoid creating many custom exceptions - it is better to use the "widely understood" standard exceptions, and only "create a custom exception type when you need to annotate the exception with additional information to aid in the programmatic handling of the symptom."
However, this seems somewhat in contrast to the idea that you should "throw exceptions at the right level of abstraction". Looking at an example from Uncle Bob's 'Clean Code' the following examples are provided for an Employee class:
Bad: public TaxId getTaxId() throws EOFException
Good: public TaxId getTaxId() throws EmployeeDataNotAvailable
So, how do I consolidate these two "recomendations" - that you should only throw exceptions at the right level of abstraction, and you should rarely create custom exception classes. In addition, when searching for information on the standard exceptions in Java, there is very very little well presented and formatted information on what standard exception classes are available - I'm looking for standard exceptions that would semantically still seem to be appropriate for calling classes, but not finding much to go on. Of course you can find the what exception classes are available in the jdk documentation, but just the general lack of info and discussion online seems strange.
So, this is where I'm at right now. Any suggestions and comments are much appreciated!
The level of abstraction is judged to be right or wrong by the user of your code. To justify an existence of AExeption and BException there should be a use-case where the user differentiates between them, e.g:
} catch(AExeption ae) {
// do something
} catch(BException be) {
// do something different
}
as opposed to always:
} catch(AExeption ae | BException be ) {
// do something
}
My experience is that real world systems tend to go easy on the amount of logic that goes into the programmatic handling of the symptom
I don't think there's an specific answer for your question. In my projects, I tend to follow these guidelines for custom exception classes:
If I can encounter with an exception in a method, check if the exception can be described by any of the subclasses of Exception or, if possible, a subclass of RuntimeException. The javadocs provide enough info about the basic classes that extend from both Exception and RuntimeException and each exception class could also have more subclasses that weren't listed before e.g. IOException.
If there's no subclass of Exception or RuntimeException or any, create a custom exception class or reuse one previously created but with a distinct message. Usually, I tend to create these classes extending from RuntimeException to avoid clients of the method using try-catch blocks. If there's the need to handle the exception in the client of this method, then it should extend from Exception.
The custom exception classes are associated to a process or specific event in the application.
If developing a business application, then the name of the exception can be related to the business process you're working with. For example, if I'm developing a process that creates a bill from a set of input data (e.g. products, services, customer data, etc), then I would provide at least 2 custom exception classes:
ElementNotFoundException, probably for not finding a specific kind of input e.g. missing product or Customer#billingAddressLocation is null due to a wrong migration of the data of some customer.
BillGenerationException, generated when there's a problem after collecting the necessary data to generate the bill and in the exact process of generate the bill.
It's quite philosophical question.
But in general it means that you should create your own exception with considering of existing ones.
Example :
In case of usage some external service and this service is unavailable
, in this case I wouldn't recommend you to throw your own exception,
because "Connection Refused" or "Connection timed out" will understand
on the spot every programmer after you, for checking your custom
exception programmer will need to go to source code and spend some
time to understand your exception after noticing it in production
logs.
But if I see that my wrapper will be clearer for such case I am adding my wrapper.
There is no contradiction between using exceptions of the right level of abstraction and refraining from creating new exception classes. What you must do is choose the most appropriate existing exception class for the particular method you are interested in if you can.
So if the clear meaning of a getTaxiId method does not suggest the method performs I/O, declaring it to throw an IOException of any kind would be inappropriate. You would then have to search the other existing exception classes for a more approriate exception class. If you did not find such a class, you know it is appropriate to create a new exception class.
I think Uncle Bob is looking at the problem from the wrong end.
You throw an exception to unravel the call chain and inform a non-local piece of logic that something unexpected and detrimental happened and allow it to respond.
I can understand wrapping an EOFException and all sorts of bad data problems into some generic InvalidDataException but providing a specific EmployeeDataException seems like overkill.
It may be useful for the calling process to (say) know that there was a local data exception and not, for example, a lost connection. That way it could abandon a unit of work but realistically continue trying to process the next one.
So, do throw at an appropriate level of abstraction - for the catcher to respond usefully.
If you think about it, if you create a different exception for each object type, someone will have to maintain catchers for all object types in play!
Tomorrow a new exception called AddressDataException is introduced and various (obscure) catcher chains need that added as yet-another-data-exception category.
Of course the answer is to introduce a DataException category as super-class to all those specialised ones.
But as soon as you do that you'll change all the handlers to catch the generic exception and realise that the correct level of abstraction is a generic DataException because that's what is useful to the catcher.

Should exceptions without messages be thrown?

Should exceptions without messages ever be thrown? In what cases? For example, when subclassing Exception, should a constructor with no parameters even be given?
public class LexerException extends Exception {
public LexerException(String message) {
super(message);
}
}
or
public class LexerException extends Exception {
public LexerException() {
super();
}
public LexerException(String message) {
super(message);
}
}
Should exceptions without messages ever be thrown? In what cases?
An exception without a message will be thrown any time some code instantiates and throws an exception without a message. Anyone can write code like that.
Of course, if the exception that you are trying to throw does not allow you to instantiate it without a message ... or a with null message ... then you can't. But I've never come across an exception class that insists that the exception is non-null.
One case where exceptions typically have no message is NullPointerException when it is thrown by the JVM itself.
If you are asking should it ... in the sense of whether it is good practice to write code that throws exceptions without a message, the answer is (IMO) No. But you can make up your own mind. (I guess, if the exception name says all that there is to be said, then a message would be redundant. However, it is always useful to have extra information in the stacktrace when debugging.)
Re these comments:
Generally, you should avoid custom exceptions. Use ones that already exist. – mre
Why should I avoid custom exceptions? – Kyranstar
The point is that before you code a custom exception, you should look to see if there is an existing exception that means the same thing as your proposed new one. For example, don't write a custom IllegalLexerArgumentException exception when there is an existing IllegalArgumentException that would serve your purposes.
Why?
For the same reasons that we don't write (say) custom collection classes without good reason. It is a bad idea to write unnecessary code, 'cos that is just more code to compile and test, more space at runtime, more code for the maintainer to read, etc.
Because having lots of exception classes that mean the same thing can make exception handling messy. This effect gets worse as you combine / reuse more libraries to make large applications.
If you don't give the exception any message so you can pop-up the message into anther position when you get the error, but it's recommended to give every exception you create a message and to create an instance of this exception and to throw it.
If the documentation explicitly states there is a single case triggering the exception, then IMHO it is not require to have a message in the exception. Otherwise, it is. A good rule of thumb is: Make it easy for whoever is going to use/debug that code.
Well, honestly I've just searched our code and we use Exceptions without messages, but they are really obvious ones. Like:
UsernameCantBeEmptyException// example only
I think this depends on the use case. The NullPointerException for instance has no message. What could be helpful? No idea. On the other hand there where versions of java where the ClassCastException had no message. That's extremly annoing as the type that should be casted is hart to figure out and is available to the program.
As long as I've no idea for a use case where skipping the message seems appropiate, I'd provide no empty constructor. AFAIK a lexer figures out things like this variable has that type and thus that acion is appropriate or not. This would indicate that the exception message might even have to be presented to he end user. In such a case even localization might be mandatory. If so even some 'factory infrastructre' might be a good idea.
On custom exceptions in general: There's been a tendency to do that to often and then many figured out that in fact no custom exceptions have ever been needed. And in fact there are even hudge programs that need not a single one. On business I work on a 200kLOC program and I don't think we have one. But for sub-systems with specific needs on handling (Like catching all the LexerException to show them in a specific way, separate them from programming bugs in your own code, whatsoever) it might make much sense to have a few. I'm working on a small OSS project and there I have even more than one. But you should always keep in mind that additional exception type must make the exception handling simpler not more complicated. If you often have several catch block one after another, then your definitly on the wrong track. That's a typical symptom of unnecessary custom exceptions.

Is there an advantage to wrapping exceptions with Custom exception types in Java

I have a class XYZ whose public functions throw Exceptions.
I have been advised that all public functions exposed by XYZ should throw exceptions called XYZDataException or XYZSystemException. So even if I get other exceptions within the public methods they need to be wrapped by these XYZExceptions.
I have a couple of questions:
What is the advantage of wrapping exceptions with XYZException?
What is the advantage of differentiating between System and Data exceptions?
To me it feels right to just throw whatever exception occurs without wrapping it further.
A lot of Exception handling depends on how you plan on extending it later on. For example, if developer B came along and wanted to modify some of your code, it would be a lot easier if he understand what Exception meant what in which case. In that case, having specific Exceptions makes more sense.
As to breaking up System and Data exceptions - a Data exception would basically be something that should be non-fatal that occurs because of bad data. A System exception would be because your System failed in some way. Again, this all points to how you want to use it later on. If you want to use your code solely, and you don't care about how your exceptions come back out, then by all means, go with what is easiest at the time.
I have found that when working with other developers on a project, it is a lot easier for them to grasp what is going on when you subclass your Exceptions and throw them in specific cases.
Hope this helps!
Yes, it means they can be explicitly caught by code that knows how to handle them.
for instance, imagine you had:
class MyRecoverableException extends Exception {
...
}
You could then have code that can differentiate between them automatically, and react accordingly, such as:
try{
// ... do something ...
}catch(MyRecoverableException e) {
// Recover
}catch(Throwable t) {
// Log fatal reason, and exit gracefully.
}
Obviously how many you need is a problem to be solved by you, the application developer, but a clean separation can make all the difference when working out what went wrong, and subclassed exceptions can hold additional properties, used to pass pertinent information to handlers about the exceptional circumstances that brought them about.
Having a base type to extend from for your application/library never hurts either - if for no other reason than to allow separation of source when logging - but the exact hierarchy and complexity required beyond that depends entirely on the project. Some designs have natural and obvious choices, some require a bit more forethought (and occasionally a bit of afterthought and refactoring).
As usual, "it depends". As a general rule it does not make sense to blindly create an exception hierarchy on a per-class basis. App-specific exceptions should group exceptions in a way meaningful to that particular app, so there might be a top-level exception, then sub-classed exceptions for things like the data layer, communication layer, utilities, whatever.
The advantage is that higher levels dealing with those exceptions are not exposed to the implementation details that generate those exceptions. Also, perhaps to a lessor degree, exceptions may be grouped more meaningfully (is it relevant that it was an IOException, or is it enough to know there was a problem writing to whatever output store you're using).
Another great advantage is that app-specific information may be captured in the custom exceptions. Things like user IDs, account numbers, etc.--any application state--which must be stored as part of a string message in a "stock" exception may be assigned to a property. This may avoid random parsing issues if you actually do anything with the exceptions or try to trace through a particular event stream.
According to msdn:
To wrap an exception, you specify it as the inner exception of a new exception and then throw the new exception. This practice should be used only in situations where the original exception is not meaningful to the person who receives the exception, or the call stack for the exception is misleading or uninteresting.
Suppose method M1 is documented as throwing an exception of type X when some condition occurs. M1 calls method M2, which happens to throw an exception of type X which M1 is not prepared to handle. If M1 doesn't catch the exception from M2, the caller is unlikely to figure out that the exception thrown out of M1 isn't an X thrown by M1, but is instead an X thrown by M2, and its practical meaning and implications may be very different. Having M1 throw an exception of a type which will never be thrown by M2 may avoid this issue (though there could still be trouble if M2 could call M1 on some other object).

java.lang.Exception vs. rolling your own exception

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?
More in depth discussion: Custom exceptions: When should you create them?
Reason one:
Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.
Basically, if someone has to write:
catch(ExistingException e) {
if({condition}) {
{ some stuff here}
}
else {
{ different stuff here}
}
}
You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.
Remember: your new Exception can be a subclass of RuntimeException
Reason two:
API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:
interface MyInterface {
void methodA();
}
class MyImplA {
void methodA() throws SQLException { ... }
}
class MyImplB {
void methodA() throws IOException { ... }
}
Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...
I believe that:
catch (Exception e) {
...
}
... is an antipattern that should be avoided. You might want one centralized broad catch somewhere in your application, to log an error and prevent the whole application from terminating - but having them scattered around willy-nilly is bad.
Why:
try {
if(myShape.isHidden()) {
throw new Exception();
}
// More logic
} catch (Exception e) {
MyApp.notify("Can't munge a hidden shape");
}
So you try this, and due to a coding error, myShape is null. A NullPointerException gets thrown when the runtime tries to derefence myShape. This code reports a hidden shape, when it should be reporting a null pointer.
Either make your own exception, or find a suitably specialized exception in the API. It's not as if extending Exception or RuntimeException is onerous.
When I want to treat my exceptions differently from everybody else's. If I want to catch mine and propagate everyone else's, or if I want to catch someone else's and propagate mine, or if I want to catch both but treat them differently, then I will define a separate class for my exceptions. If I want to treat them all the same, either by propagating both or by catching both (and doing the same thing either way with the caught exceptions), the I will use the standard class.
IF there is an existing Exception with the language runtime or libraries, use it ELSE create your own, document it well and that should work in 99% of the cases.
Software captures meaning.
There are almost no reasons for throwing an existing exception: the JVM already does that for you. Your version of their exception isn't really accurate and throwing "Exception" isn't meaningful, either.
You might have a DataFormatException because of a parsing algorithm you wrote. This, however, is rare.
When your program encounters an exceptional situation, it's almost always unique to your program. Why force-fit your exceptional situation into an existing exception? If it's unique to your program, then... well... it's unique. Name it that way.
Do not, however, provide a unique exception class for each unique message. One exception class can have many variant messages and supporting details.
The Python rule of thumb, translated to Java, is to define any unique exceptions at the package level. [In Python, they suggest exceptions at the "module" level, something that doesn't precisely translate to Java.]
Start always by using the common exception classes and then when a need appears to handle it specially, change it.
When creating a method first time, just let exceptions go through.
If there are exceptions that must be handled, those can either be just defined in throws or wrapped to some runtime exception or wrapped own throws exception. I prefer runtime exceptions in many cases. Defining throws definition should be avoided until there is a need for it from API point of view.
Later when a need appears to do specific handling for an exception in some caller, come back and create new exception for it.
The point is to avoid doing extra work before knowing what is needed.
I can't imagine specifically throwing a java.lang.Exception if some object/class/method had a problem. It's too generic - if you're not going to create your own Exception class, seems to me like there ought to at least be a more specific Exception-type in the API.
I would use the exceptions from the Java API when the exception relates to the API. But if an exceptional situation arises that is unique to my own API then I will create an Exception for it. For example if I have a Range object with two properties min and max and the invariant min <= max then I will create an exception InvalidRangeException.
When I am writing code this helps because I know if the exception originates because I violated one of my own conditions or its something from the Java API.
In most cases it doesn't make sense to create your own exception class.
There is a tendency in novice programmers to create their own exception class just so they can use a name that is more indicative of the type of error. So you'll find classes like FTPInitializationException, DAOFactoryException etc. even though such exceptions are not being handled differently than standard exceptions. This is clearly an anti pattern that should be avoided.

Categories