Is there any alternative in java to make code possible in jdk1.6. I know same is possible in jdk 1.7, but i am stuck with jdk1.6.
Below code can catch multiple exceptions and i want to handle these exception and add it to database table. Since for all 3 exceptions, my exception handling logic is going to remain same. I don't want repeat same code for multiple catch blocks.
try{
//do somthing here
}catch(CustomException1 ex1 | CustomException2 ex2 | CustomException3 ex3){
// Here goes common Exception handing logic.
}
try{
//do somthing here
}catch(Exception e){
if(e instanceof CustomException1 || e instanceof CustomException2 || e instanceof CustomException3 ) {
// Here goes common Exception handing logic.
} else { throw e;}
}
There is no other option I think.
This syntax was added in Java 1.7 because it was difficult to do it cleanly before.
There are a few things you can do:
Use a single catch for a common base class of CustomExceptionX (usually Exception, but sometimes you have to go up to Throwable if one of these is actually an Error). The drawback is that it will also catch RuntimeExceptions, so you will have to do a runtime check like Subin suggests. If you are the one defining the CustomExceptionX, you can define a common superclass for this usage and you won't have to do a runtime check.
Put your common logic in a function and call this function in both catches. This way the only duplication will be the call to the function.
It is not possible in the jdk1.6. I have just found an alternative. what you can do is define a class level variable.
Object c ;
then in your corresponding catch block assign the reference.
catch(CustomException1 cx1) {
c= cx1;
}
catch(CustomException2 cx2){
c = cx2;
}
if( c instanceof cx1 || c instanceof cx2)
// put your common logic here
i hope it will solve your problem.
I finally went ahead with this code,
try{
//do somthing here
}catch(SuperExceptionClass ex){
if (ex instanceof CustomException1 || ex instanceof CustomException2 || ex instanceof CustomException2) {
// Here goes common Exception handing logic.
} else {
throw ex;
}
}
Related
In one of my software, I'm using a library that is basically a protocol implementation. The library is structured according to the five first OSI layers (physical to session).
I have to use the session layer with this interface
public interface ReadSession {
Iterable<byte[]> read(boolean fromStart, byte dataset, int nbData) throws SessionException;
}
Now my problem is that, according to the inner (or inner's inner, etc.) cause I need my software to behave differently.
Examples (> represents the inner cause relation):
If SessionException > IOException > ... then I should abort all the communications
If SessionException > TransportException > NetworkException > ... then I should log the exception and proceed with the next communication
If SessionException > TransportException > GatewayException > ... then I should warn the user that there's a problem with its gateway
But all what I have at the moment is a single catch
catch(SessionException e) {
//How to handle this problematic properly ?
}
I feel myself not comfortable with a fixed number of call to getCause() because:
of the lot of null checks involved
I rely on the implementation details of the library (leaky abstraction) and if these change in the future I'm screwed
Has anyone already faced such a situation and want to share his knowledge about how to handle it as cleanly as possible ?
One approach here is to create a List of the causes in your single catch block.
For example:
catch (SessionException t)
{
List<String> causeList = new ArrayList<>();
do
{
causeList.add(t.getClass().getName());
t = t.getCause();
} while(t != null);
}
Then what you can do is compare the causeList with a set of predefined cause lists that you hardcode. When you find that the causeList equals one of your predefined lists, then you take the appropriate path of code.
A predefined List can look something like:
final List<String> ABORT_LIST = new ArrayList<String>
(Arrays.asList("com.package.SessionException", "java.io.IOException"));
Then, after you build the causeList in the catch block, you can do something like this:
if (causeList.equals(ABORT_LIST))
{
System.out.println("Aborting...");
}
I ended up using something like this:
catch(SessionException e) {
Throwable cause = e.getCause();
while(cause != null) {
if(cause instanceof NetworkException.class) {
//Trigger some logic
}
else if(...)
cause = cause.getCause();
}
}
I have several functions where I am casting an object to an explicit type.
The problem is, when this object is created, the type may not match the type I am casting to. Somewhere along the line there are some conversions that take place. However, it is possible the code never reaches these conversions. The fact that it doesn't is not an issue.
So when the code reaches the point where the casting will occur, all I need to do is put the part into a try catch block. In fact I don't even need to handle the exception in any special way.
But I have a lot of these functions. I would like to know if there is some way to wrap lines of code with a try catch block without actually writing out the try catch block. If I can call some function some how that will do it automatically.
try
{
// cast something
}
catch( ClassCastException e )
{
}
Instead I want to call a method that will put the try catch block around // cast something. Is there any way to do something like this?
Note: I don't do anything when I catch the ClassCastException. It is okay if I can't cast the object correctly, but I need to catch the exception so the code execution won't jump to some other place.
You can write a method like this to do the casting for you while ignoring any ClassCastException.
public static <I, O> O cast(I input, Class<O> outClass) {
try {
return outClass.cast(input);
} catch (ClassCastException e) {
return null;
}
}
You can use it like this:
Number n = new Integer(1);
Integer i = cast(n, Integer.class);
But you can also improve the code to avoid exceptions:
public static <I, O> O cast(I input, Class<O> outClass) {
if(outClass.isAssignableFrom(input.getClass())) {
return outClass.cast(input);
} else {
return null;
}
}
Not really, because this doesn't make any sense. If there's nothing you need to do when you catch the exception, then don't call the operation at all and delete all the code after. If it doesn't matter whether the operation succeeds or fails then don't call it in the first place.
More seriously - ahem, that was serious - you can not catch the exception and let the caller deal with it.
Try to create a common method that does this casting for you
private MyTypeOfObject cast (Object obj) {
try {
// your casting code
return newObj;
} catch (ClassCastException ee) {
// log and ignore
return null; // ????
}
}
There's nothing that I know of to do this (other than what #Scary_Wombat said) but if I were in your shoes I would just write a simple code generator to handle these repetitive/boilerplate cases using some templating engine like Freemarker or something more advanced like Antlr. There are tutorials about the place on each.
Let's say I have a SOA. Now I make a service call and I get an object which has nested objects as field. Let's say:
class A {
B b;
}
class B {
C c;
}
class C {
D d;
}
Now if I need to access a field from class D when I get object as a response from a service call i need to perform :
if(a == null || a.getB() == null || a.getB().getC() == null || a.getB().getC().getD() == null) {
throw someexception();
}
Is there a graceful way of handling the same predicate?
You can use Optional:
D d = Optional.ofNullable(a)
.map(A::getB)
.map(B::getC)
.map(C::getD)
.orElseThrow(MyNullException::new);
You can also do orElseGet(D::new) if you want to use a default value instead.
In your specific example, you're throwing an exception. That being the case, this is apparently an exceptional condition, so we can use exceptions to manage it:
D d;
try {
d = a.getB().getC().getD();
}
catch (NullPointerException npe) {
throw new SomeException(npe);
}
doYourStuffWith(d);
If you weren't throwing an exception, you wouldn't do that; you don't want to use exceptions for normal program flow. In that situation, your current check is fine, or you could use more specific exceptions with a series of if/else, or in a Java 8 context do that lovely thing Peter showed us. :-)
Have you tried something like this?
try {
//Try and do something
} catch(NullPointerException e) {
//Something was null, therefore an exception was thrown
}
Which one will be better: ErrorCode or Exception for that situation?
I have ever been seeing these two error handling techniques. I don't know the disadvantages and advantages for each technique.
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be ChildRecordFoundException, ParentRecordNotFoundException
* NullValueFoundException, DuplicateException, etc..
*/
throw translateException(e);
}
}
or
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be "CHILD_RECORD_FOUND, "PARENT_RECORD_NOT_FOUND"
* "NULL_VALUE_FOUND", "DUPLICATE_VALUE_FOUND", etc..
*/
String errorCode = getErrorCode(e);
MyException exc = new MyException();
exc.setErrorCode(errorCode);
throw exc;
}
}
For second method, the error code retrieve form configuration file. We can add Error Code based on the SQL Vender Code.
SQL_ERROR_CODE.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED
Caller client for method 1
try {
} catch(MyException e) {
if(e instanceof ChildRecordFoundException) {
showMessage(...);
} else if(e instanceof ParentRecordNotFoundException) {
showMessage(...);
} else if(e instanceof NullValueFoundException) {
showMessage(...);
} else if(e instanceof DuplicateException) {
showMessage(...);
}
}
Caller client for method 2
try {
} catch(MyException e) {
if(e.getErrorCode().equals("CHILD_RECORD_FOUND")) {
showMessage(...);
} else if(e.getErrorCode().equals("PARENT_RECORD_NOT_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("NULL_VALUE_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("DUPLICATE_VALUE_FOUND") {
showMessage(...);
}
}
I recommend using Spring's JDBCTemplate. It will translate most existing databases' exceptions into unchecked exceptions that are specific, e.g. DataIntegrityViolationException. It will also include the original SQL error in the message.
Strange question, since both approaches do the same thing: they transform a checked SqlException in a different exception which seems to be unchecked. So the first one is the better one because it moves this into a single method.
Both leave some questions to be asked:
Isn't there some infrastructure that can do this conversion (Spring Template was mentioned in another answer)
Do you really want checked Exceptions, in my mind they are hardly ever worth the trouble.
Who is doing the real handling of the exception, does it get all the information needed? I would normaly expect some additional information about the transaction that failed inside of MyException, like: What did we try to do? (e.g. update a busines object); On what kind of object? (e.g. a Person); How can we/the user Identify the object (e.g. person.id + person.lastname + person.firstname). You will need this kind of information if you want to produce log/error message that tell you or your user more than 'Oops, something is wrong'
Why is MyException mutable (at least in the 2nd example)
A better design than either one would be to make your custom exceptions unchecked by extending RuntimeException.
I'd want your exception to wrap the first one, so coding it this way would be better, too:
MyException exception = new MyException(e); // wrap it.
If you do that, the second one is preferred. More information is better.
IMHO, it depends as how tightly your code is coupled with SQL.
If the method is to always (*1) be coupled with SQL, I would just declare and rethrow the SQLException (after cleanup / closing resources). Upper methods that are SQL-aware would then process it as they see fit (perhaps they need all the detail, perhaps they not).
If sometime in the future you could change the method for another which does not use SQL, then I would go for the second option.
(1): Be extra pessimistic with this assumption: "I think we are not going to change" should be interpreted as "Probably we will want to change". "We are not going to change" means "We cannot change without breaking lots of other methods anyway".
One differnce would the way you will catch the exception. In the first cases you can just catch the exception and you know what the error is. In the second case you have to catch the exception and check the code to see what the error is.
In java, Which of the following is the more "accepted" way of dealing with possibly null references? note that a null reference does not always indicate an error...
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
or
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
}
The answers already given are excellent (don't use exceptions for control flow; exceptions are expensive to throw and handle). There's one other important reason specifically not to catch NullPointerException.
Consider a code block that does the following:
try {
reference.someMethod();
// Some other code
}
catch (NullPointerException e) {
// 'reference' was null, right? Not so fast...
}
This might seem like a safe way to handle nullity of reference ...but what if reference was non-null and someMethod() raised NPE? Or what if there was a NPE raised elsewhere in the try block? Catching NPE is a surefire way to prevent bugs from being found and fixed.
Catching exceptions is relatively expensive. It's usually better to detect the condition rather than react to it.
Of course this one
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
we shouldn't rely on exception for decision making, that aren't given for that purpose at all, also they are expensive.
Well If you aren't making decision and just verifying for initialized variable then
if (reference == null) {
//create new reference or whatever
}
//use this variable now safely
I have seen some auto code generator wraps up this thing in accessors/getter method.
I think in general an exception should be reserved for exceptional circumstances - if a null reference is sometimes expected, you should check for it and handle it explicitly.
From the answers its clear that catching an exception is not good. :)
Exceptions are definitely not free of cost. This might help you to understand it in depth. .
I would also like to mention an another practice while comparing your object with a known value.
This is the traditional way to do the job: (check whether the object is null or not and then compare)
Object obj = ??? //We dont know whether its null or not.
if(obj!=null && obj.equals(Constants.SOME_CONSTANT)){
//your logic
}
but in this way, you dont have to bother about your object:
Object obj = ???
if(Constants.SOME_CONSTANT.equals(obj)){ //this will never throw
//nullpointer as constant can not be null.
}
The first one, throwing exceptions is a costly operation.
The first form:
if (reference == null)
{
//create new reference or whatever
}
else
{
//do stuff here
}
You should not use exceptions for control flow.
Exceptions are for handling exceptional circumstances that would not normally occur during normal operating conditions.
You should use exception catching where you do not expect there to be an error. If something can be null, then you should check for that.
maybe the try catch approach will start making sense in this situation when we can start doing
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
retry;
}
This is related to your style of development, if you are developing code using "safe" style you have to use
if(null == myInstance){
// some code
}else{
// some code
}
but if you do not use this style at least you should catch exception, but in this case it NullPointerException and I think preferably to check input parameters to null and not wait to throwing exception.
Since you asked for Best Practices, I want to point out that Martin Fowler suggests to introduce a subclass for null references as best practice.
public class NullCustomer extends Customer {}
Thus, you avoiding the hassle of dealing with NullPointerException's, which are unchecked. Methods which might return a Customer value of null, would then instead return a NullCustomer instead of null.
Your check would look like:
final Customer c = findCustomerById( id );
if ( c instanceof NullCustomer ) {
// customer not found, do something ...
} else {
// normal customer treatment
printCustomer( c );
}
In my opinion, it is permissible in some cases to catch a NullPointerException to avoid complex checks for null references and enhance code readability, e.g.
private void printCustomer( final Customer c ) {
try {
System.out.println( "Customer " + c.getSurname() + " " + c.getName() + "living in " + c.getAddress().getCity() + ", " + c.getAddress().getStreet() );
} catch ( NullPointerException ex ) {
System.err.println( "Unable to print out customer information.", ex );
}
An argument against it is that by checking for individual members being null, you can write a more detailed error message, but that is often not necessary.