Exception has no "cause" parameter - java

Many of the built in Java exceptions have no way to accept a "cause". Is there any way to assign a cause to these exceptions?
I want to be able to chain exceptions, like with this InterruptedException example:
try{
//threaded code
}catch (InterruptedException e){
throw new InterruptedException("context-specific information", e);
}
If a constructor like this does not exist, what is the reasoning?
Edit: I've considered throwing either a different exception or runtime exception that accepts a cause parameter. The reason I haven't gone with either of these options is because I'm working within a framework that expects an InterruptedException, and not some other exception type.

The logical reason for an exception class missing a way to attach a cause, is that they can't have another exception as a cause.
Taking the exceptions given as examples, we've got InterruptedException and UnsupportedAudioFileException. Neither of those will have an exception as a cause, since InterruptedException cannot occur because of other exceptions, but only if a thread is interrupted.
UnsupportedAudioFileException on the other hand could take a cause, but it would be useless. There's no "deeper" reason for an audio file to not be supported.
Therefore it's no suprise that NullPointerException doesn't take a cause either. It's not like there are many reasons for that to happen...
If you're using an exception that doesn't take a wrapped exception in the constructor, you're probably using an exception that wasn't designed for that sort of use. While the ready made "general exceptions" like IllegalArgumentException do take (and even expect) causes to be included, if you can't find an existing one that fits your use case, create your own exception.
If you're working with a framework that expects an InterruptedException, there are 2 possibilities. Either it was chosen because of the name ("Hey, stopping this job should throw InterruptedException") or it was chosen because of sane design choices. You should first make sure you're not using the framework wrong, since InterruptedException is not a general use case exception and implies interrupted threads.

Is there any way to assign a cause to these exceptions?
Yes; you can use the initCause(Throwable) method, which allows a cause to be set. It can only be called once for a given exception instance; it's specifically intended for this sort of case.
If a constructor like this does not exist, what is the reasoning?
Oddly enough, even though the great majority of JDK exceptions do support taking causes, the Javadoc for java.lang.Throwable seems to suggest that that's not the expected default. The Javadoc describes a few reasons that you might want to wrap an exception (neither of which applies in your case: they both have to do with wrapping an exception of one type in an exception of a different type), and it says that the cause-accepting constructors should only be created for "throwable classes that wish to allow causes to be associated with them" or even just for "subclasses that might likely have a cause associated with them" (emphasis mine).
I wonder if it's just that the JDK is behind the times; apparently causes were not originally intended to be used quite as generally as we now expect?

Related

Using exception classes to model errors

I want to know whether it would be right to use exception classes as regular classes to handle application errors (just regular controlled errors, not exceptional ones), without throwing them with the proper language clause (eg. instantiating them and returning them from a method). I've been discussing this topic recently with some colleges and I think that exceptions should only be used as exceptions, but I'd like to listen to more opinions.
What you mean by "controlled error" is actually known by the name checked exception.
"Exceptional exceptions" are known as unchecked exceptions.
The difference is explained here: Checked vs Unchecked exception
So, you see: Java comes with a built-in mechanism to distinguish between
exceptions caused by programming mistakes (e.g. NullPointerException when passing unexpected null as an argument) -- unchecked exceptions
versus anticipated exceptions that should be handled by the caller (e.g. IOException when some kind of I/O went wrong) -- checked exceptions
Returning instances of Exception (or any subclass) would be considered a misuse in virtually all circumstances.
You could ask your colleague how he/she would implement an exceptional outcome of a method with this signature:
public String createStringOrFailWithException();
Returning an Exception? Certainly not, because this requires a different return type.
Throwing the exception instead allows you to keep the return type, and to benefit from vast exception handling capabilities, including finally blocks and try-with-resources statements, to give only two examples that you don't want (should not) implement by yourself.
I suggest keeping Exceptions "exceptional". I.e. don't build them into your app logic. Use more meaningful things like a ActionXResponse class etc that could indicate failure, and even have an Exception as a property which the controller could check for "controlled exceptions". It's much more meaningful when you have your own class as a response.
Another guideline I'd suggest, along with keeping Exceptions "exceptional" is to avoid checked Exceptions (compile-time).

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?

java - finding out which type of exception to throw

I am confronting with the following issue for some time.
Let's say you have some code and at some point you need to throw an exception. Let's suppose we want to throw a runtime exception.
Java comes with plenty of exceptions and, in some cases, you may find one suitable for your case.
The problem is how can I figure out which of the exceptions is most suitable for my case?
My question is only about the existent Java implementations of RuntimeException and not custom exception which are extending this class.
Let's take an example. I have the following switch statement:
switch(something){
case A: ... break;
case B: ... break;
default: throw new AJavaRuntimeException("No such case defined");
}
What should I use instead of AJavaRuntimeException and comes with Java? How to find the proper exception through Java?
The easiest solution would be to extend RuntimeException and create NoSuchSwitchCaseDefinedException. Or even throw a RuntimeException. But... Maybe Java already has something for this.
Browsing the API for Direct known subclasses of RuntimeException will probably get you your best fit out of the "catalog".
In this case, you could either throw:
IllegalStateException, signalling an illegal state in your program or
IllegalArgumentException, signalling a bad argument
Etc...
If you can't find your exact match, you shouldn't hesitate to extend Exception or RuntimeException depending on your requirements (checked vs not checked).
If you need to throw an exception independently, better throw a custom user defined exception and it has to be checked one.
Never throw runtime exceptions on your own.
Create business exceptions and throw them.
There are many philosophies to follow here. The philosophy I follow is that unchecked exceptions (i.e. everything inheriting from RuntimeException or Error) are solely used to report programming errors (e.g. though an error dialog or a log message). Programming errors should only be handled in a generic way (e.g. by aborting an operation, skipping an optional processing step, etc.). This means that the actual type used for the exception does not matter in a technical sense.
What does matters is that the exception, its name, its message, its accompanying JavaDoc comment make it as simple as possible to identify what triggered the bug, what a possible workaround might be and how to fix the bug in the end.
If you are writing a library that might fail because of incorrect usage, having domain-specific unchecked exceptions might make working with the library more pleasant because you have the opportunity to provide a lot of context and documentation to an error that might otherwise be obscure.
If you are writing an end-user application or service, you or your time are probably one of the only people ever seeing those exception so that extra work might not be worth it and just throwing RuntimeException with a short description of the problem as its message might be enough.

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).

Should I put throws IllegalArgumentException at the function?

I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException class as it seemed right name for the issue, but should I put the throws IllegalArgumentException at the function definition ?
I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.
RuntimeExceptions like IllegalArgumentException are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.
Potential RuntimeExceptions should be documented somehow in the function contract (i.e. javadoc), either with the explicit #throws, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.
If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.
There's two types of exceptions:
runtime exceptions (like IllegalArgumentException and NullPointerException for example) don't need to be explicitly caught, because they 'shouldn't happen'. When they do, of course, you need to handle them somewhere.
regular exceptions NEED to be caught or declared to be thrown because they represent a more intrinsically difficult kind of error.
You need to read up on Unchecked Exceptions - exceptions which inherit from RuntimeException. They don't need to be declared in the method header.
http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
The last paragraph sums it up:
If a client can reasonably be expected
to recover from an exception, make it
a checked exception. If a client
cannot do anything to recover from the
exception, make it an unchecked
exception.
IllegalArgumentException (along with some others, for example NullPointerException) are examples of a RuntimeException. This type of exception is not what's known as a checked exception. Java requires that methods declare which checked exceptions they throw and that if a called method might throw a checked exception, the calling method should either declare that it throws the exception itself, or catch and handle it.
As such, my concrete recommendation would be no, don't declare it. Certainly, though, you don't want to be catching it. In most cases, you also don't want to be throwing it unless this is unexpected behaviour. If it's quite normal and reasonable for the the method to be getting a value it doesn't like, an Exception is the wrong way to handle it.
You might also want to consider making use of assertions.
the first point when understanding exceptions is that they are for exceptional situations. While thinking about your method you must ask: "Should this method throws an exception if an exceptional value is passed through?" If the answer is "yes", put it in your method declaration.
I don't know if you get the idea, but it's kind of simple. It's just a matter of practice.

Categories