Add to Google Reader or Homepage

Handling java.lang.illegalstateexception

java.lang.illegalstateexception:

In this post i am going to discuss about the java.lang.illegalstateexception. Let us see What is meant by this exception?When will be this exception is thrown? and how to fix it?

What is meant by illegalstateexception?

As you read the name of this exception you can able to understand that a particular framework used in your program is under illegal state.Lets have a look at this exception in detail.

This exception may arise in your program mostly if you are dealing with the collection framework of java.util.package.There are many collections like List,Queue,Tree,Maps.Out of which List and Queues(Queue and Deque) tend to throw this illegal state exception at particular conditions.Note that this exception is not just limited to this Collection Framewok.

When will be this exception is thrown?

In java API it is given that "this exception will be thrown, when we try to invoke a particular method at an inappropriate time."Let us see what are the situations on which this exception will be thrown.

1.In case of List collection we use next() method of the Iterator interface to traverse through the
List.We know about the remove() method which is used to remove a particular item in the list.

In order to remove the first  object from the list that contains string objects,we have to follow these steps:

List li=new LinkedList();
-----
-------
Iterator i=li.iterator();
i.next();   // visits the object
i.remove();//removes the object

If you call the remove() method before (or without) calling the next() method then this illegal state exception will be thrown as it will leave the List collection in an unstable state.


Similarly, if you want to modify a particular object we will use the set() method of the ListIterator() interface as follows:

List li=new LinkedList();
-----
-------
ListIterator i=li.listIterator();
i.next(); //visits the object
i.set("hello");//modifies the object

Note:

"If you have modified the list after visiting the object ,then using the set() method will throw this illegalstateexception" .

Have a look at this,

ListIterator i=li.listIterator();
i.next(); //visits the object
i.remove();//this statement removes the object thereby modifying the list structure.
i.set("hello");//Now,using this set() method will throw an illegalstateexception.

2.In case of queues, if you try to add an element to a queue,then you must ensure that the queue is not full.If this queue is full then we cannot add that element, thus causing this exception to be thrown.

Examples situations of this exception:

Queue:


import java.util.*;
import java.util.concurrent.*;
public class Unsupport
{
public static void main(String args[])
{
BlockingQueue s=new ArrayBlockingQueue(3); //queue size is 3
s.add("Ram");
s.add("Ganesh");
s.add("Paul");
s.add("praveen");
s.add("Banu");
System.out.println(s);
}
}


Exception in thread "main" java.lang.IllegalStateException: Queue full
        at java.util.AbstractQueue.add(Unknown Source)
        at java.util.concurrent.ArrayBlockingQueue.add(Unknown Source)
        at Unsupport.main(Unsupport.java:11)

In the above program i have set the queue size equal to size 3 ,thus adding elements beyond the size will throw this exception.

LinkedList:


import java.util.*;
public class Unsupport
{
public static void main(String args[])
{
List s=new LinkedList();
s.add("Ram");
s.add("Ganesh");
s.add("Paul");
s.add("praveen");
Iterator i=s.iterator();
i.remove(); // the next() method is not used before the remove() method   
System.out.println(s);
}
}

Exception in thread "main" java.lang.IllegalStateException
        at java.util.LinkedList$ListItr.remove(Unknown Source)
        at Unsupport.main(Unsupport.java:12)

Here i forgot to use the next() method which causes this exception.


import java.util.*;
public class Unsupport
{
public static void main(String args[])
{
List s=new LinkedList();
s.add("Ram");
s.add("Ganesh");
s.add("Paul");
s.add("praveen");
ListIterator i=s.listIterator();
i.next();
i.remove();// modifying the list
i.set("kalai");
System.out.println(s);
}
}

Exception in thread "main" java.lang.IllegalStateException
        at java.util.LinkedList$ListItr.set(Unknown Source)
        at Unsupport.main(Unsupport.java:14)

In the above program i have tried to modify the list after using the next() method which leads to this exception.

As i have told before when using set() method we have to ensure that no other actions that modifies the List is used.

Solutions:

As you all understand,when this exception will be thrown? the solution is obvious that we should avoid invoking the methods at inappropriate places.

 

How to resolve java.lang.instantiationexception

Instantiation Exception

I have discussed about this exception in detail in my new post.To have a look at it click here..

In this Post let us discuss about the java.lang.instantiation exception in detail.Let us know what is meant by this exception?why this exception is thrown? and how to solve it.

What is meant by Instantiation Exception?


There are certain classes exists for which we cannot create objects.Lets see what are those classes.

1.We all know that an abstract class cannot be instantiated.But there are some other ways available, through which we can try to instantiate a abstract class.If we use the newInstance() method for creating the object then we will not get that error at compile time.But you will get this Instantiation exception thrown.

2.An abstract class,an interface,even primitive data types like int,float,double,byte can also be represented as the Class objects.Except ordinary class other classes cannot be instantiated.

3.A class that has no default constructor i.e a constructor with no arguments.This default constructor is needed only when an argumented constructor is already defined, otherwise it is not needed.

Look at the following example to understand how to use newInstance() method

class A
{
}
class B
{
......
Class a=Class.forName("A");//representing an ordinary class
a.newInstance();
}

As you see this is another way of instantiating a class.The Class.forName() method will return the object of class Class.Using that object we can call the newInstance() method to instantiate the class A.

Similarly  for an interface like Serializable() we can do as follows

Class b=Serializable.class;
b.newInstance();

Here Serializable is an interface but i have represented it as a class using the newInstance() method.

When will be this exception is thrown?

 

When we try to instantiate the following classes using the newInstance() method, then this exception will be thrown.

1. Trying to instantiate an abstract class.

2.statements that involves instantiating an interface.

3.An array class

4.A legitimate class that has no nullary constructor.


Example situation of this exception:

instantiating an abstract class:


import java.io.*;
import java.lang.*;
import java.util.*;

abstract class Inst
{
}
class Exp
{
public static void main(String args[])throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
Class cl=Class.forName("Inst");//trying to instantiate an abstract class "Inst"
cl.newInstance();
}
}
output:

Exception in thread "main" java.lang.InstantiationException
        at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance
(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at java.lang.Class.newInstance0(Unknown Source)
        at java.lang.Class.newInstance(Unknown Source)
        at Exp.main(Exp.java:15)

 

Representing Primitive data types as class:

 

import java.io.*;
import java.lang.*;
import java.util.*;

 class Inst
{
}
class Exp
{
public static void main(String args[])throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
Class cl=int.class;//representing the integer data types as a class
cl.newInstance();
}
}

output:
Exception in thread "main" java.lang.InstantiationException: int
        at java.lang.Class.newInstance0(Unknown Source)
        at java.lang.Class.newInstance(Unknown Source)
        at Exp.main(Exp.java:13)

 

Representing an interface as a class:


import java.io.*;
import java.lang.*;
import java.util.*;

 class Inst
{
}
class Exp
{
public static void main(String args[])throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
Class cl=Serializable.class;//Representing the serializable interface as a class
cl.newInstance();
}
}

Exception in thread "main" java.lang.InstantiationException: java.io.Serializabl
e
        at java.lang.Class.newInstance0(Unknown Source)
        at java.lang.Class.newInstance(Unknown Source)
        at Exp.main(Exp.java:13)

 

Having no nullary constructor:


import java.io.*;
import java.lang.*;
import java.util.*;

 class Inst
{
int first,second;
Inst(int a,int b)    //Here there is no default constructor i.e. a constructor with no arguments
{
first=a;
second=b;
}
}
class Exp
{
public static void main(String args[])throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
Class cl=Inst.class;
cl.newInstance();
}
}

output:

Exception in thread "main" java.lang.InstantiationException: Inst
        at java.lang.Class.newInstance0(Unknown Source)
        at java.lang.Class.newInstance(Unknown Source)
        at Exp.main(Exp.java:19)

Solution:


In java, as far i know there is no way available to instantiate an abstract class or an interface or the primitive data types.So,its better to avoid these statements from the program.If this exception arises due to the absence of a default constructor,it can be overcome by  defining a no argument constructor(default constructor)




How to resolve UnsupportedOperationException:


 UnsupportedOperationException:

This is One of the most commonly experienced exception by the java programmers who deals with the immutable or unmodifiable objects.In this post lets see how to deal with this exception.Before that let us absorb what exception is this?when it will be thrown? and finally how to fix this exception.

What is meant by UnsupportedOperationException?

The UnsupportedOperationException tells us that a particular operation cannot be performed  as it was restricted for use against a particular object.This exception extends the Runtimeexception which serves as a  super class for a group of run-time exceptions.

When this UnsupportedOperationException is thrown?

As the name implies that this exception is thrown when the requested operation cannot be supported. As i have said before this exception is thrown by almost all of the Concrete collections like.
1.Lists
2.Queue
3.Set
4.Maps.

Let us have a quick overview of java collection frameworks related to our discussion.

All those collections that i have listed above are used to store some values and provides some means to traverse the values and even allows the modification of collection.We can create views for those Collections except queue.

You may wonder what is a view?.A view is a read-only format of the collections,which means that through view we can  traverse the collections and even we can retrieve values.But if you try to modify the collection using view object  this will cause an UnsupportedOperationException to be thrown.For creating Unmodifiable views java provides the following methods.

1.Collections.unmodifiableCollection.
2.Collections.unmodifiableList
3.Collections.unmodifiableSet
4.Collections.unmodifiableSortedSet
5.Collections.unmodifiableMap
6.Collections.unmodifiableSortedMap.

Note:

1.The Map collections allow the use of remove() method but does not support add() method using the view object.
2.The un modifiable views does not support either add() or remove() method.


An another important cause of this exception is the use of wrappers between the collections and the primitive types.

How to overcome UnsupportedOperationException?

As we know the cause of this exception it will be quite easy to deal with it.Since view objects do not allow
modification of the collection,the solution that i suggest you is to use the object of the collection rather than using the view object for modification.

Examples for the UnsupportedOperationException:


Use of Wrappers:

import java.util.*;
public class Unsupport
{
public static void main(String args[])
{
String s[]={"ram","ganesh","paul"};
List li=Arrays.asList(s);
li.clear();
System.out.println(" The values in the list: "+li);
}
}

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.remove(Unknown Source)
        at java.util.AbstractList$Itr.remove(Unknown Source)
        at java.util.AbstractList.removeRange(Unknown Source)
        at java.util.AbstractList.clear(Unknown Source)
        at Unsupport.main(Unsupport.java:9)

KeySet View of Map collections:

import java.util.*;
public class Unsupport
{
public static void main(String args[])
{
Map s=new HashMap();
s.put("1","Ram");
s.put("2","Ganesh");
s.put("3","Paul");
System.out.println(s);
Set keys = s.keySet();
keys.add("7");
System.out.println(s);
}
}

{3=Paul, 2=Ganesh, 1=Ram}
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractCollection.add(Unknown Source)
        at Unsupport.main(Unsupport.java:12)

Unmodifiable view of Map collections:

import java.util.*;
public class Unsupport
{
public static void main(String args[])
{
Map s=new HashMap();
s.put("1","Ram");
s.put("2","Ganesh");
s.put("3","Paul");
System.out.println(s);
Map m=Collections.unmodifiableMap(s);
m.put("7","raj");
}
}

{3=Paul, 2=Ganesh, 1=Ram}
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableMap.put(Unknown Source)
        at Unsupport.main(Unsupport.java:12)





java.lang.unsupportedclassversionerror

 UnsupportedClassVersionError:


             This Unsupported class version error is one of the common exceptions in java programming. It belongs to java.lang.package.In this post i am going to discuss about this UnsupportedClassVersion error in detail.

What is meant by Unsupported Class Version error?

      As the name indicates that the class file that you are trying to execute is not supported by this Java Virtual Machine.You may wonder why this class file is not supported? after all this is a class file containing the byte codes.

      Before going to discuss about this exception let us have a glance at the file format of the class file.We all know that the class file is formed when we compile the program..

     This class file consists of a two important version numbers. 

1.Minor version number
2.Major version number

These two version numbers decide whether this class file is supported by this virtual machine or not.

When this Unsupported Class Version Error is thrown?

      When trying to execute the class file,java interpreter first reads the magic numbers 0x CA FE BA BE   which identifies whether it is a class file or not,immediately after this magic number the version numbers are located.When the Java Virtual Machine identifies that the virtual numbers in the class file are different from what it can be able to support, then this exception is thrown.

       This exception mainly occurs if you compile the program using the Java virtual Machine of higher version and trying to execute in the JVM of lower version.

 

 How to fix this Exception?


 If there is a way available to convert your class file from higher version to lower version then your problem might be solved.Fortunately a jar package had already been developed for this purpose,which is known as "Retroweaver"

This Retroweaver enables you to convert a class file from higher version to lower version.But one of the disadvantage of this jar file is it enables you to convert only class files created using jdk 1.5 to its lower version.It does not support class files generated using jdk1.6 and other higher versions.

Search for the keyword Retroweaver in Google and download it from available links.After downloading it extract  the  file using Winzip .There you can see a folder "release" which lists some jar files.The jar file retroweaver-ex.jar provides you the graphical interface for converting the class files.

    If you use jdk 1.6 for developing your programs, I suggest you to use the same JVM  to execute the program which You used to compile it.I guess this will fix the problem.
   
You can also download the desired JVM  that supports  the class file to be executed from the internet and install it.

    
To find the class version number that your JVM supports use the following program.

Program:


import java.lang.*;
import java.util.Properties;
import java.io.*;

public class Prop
{
public static void main(String args[])
{
System.out.println(System.getProperty("java.class.version"));
}
}
Output:

50.0

Here,
Major version number: 50
Minor Version number:0

To find the version number of the class file that you are trying to execute, use the following program and supply the name of the class file as input to the program.

Program:

import java.io.*;
import java.util.*;

public class Fileclassread
{
public static void main(String args[])
{
String line;

try
{
DataInputStream in=new DataInputStream(new FileInputStream("Child1.class"));
int bytesavailable=in.available();

for(int i=0;i
{
if(in.readInt()==0xCAFEBABE)
{
System.out.println(in.readShort());
System.out.println(in.readShort());
}
}
}
catch(EOFException e)
{
System.out.println("the file has reached its end...");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

The output of the above program is as follows:

The minor version number:0
The major version number:50
the file has reached its end...


java.lang.exceptionininitializererror


ExceptionInInitializerError:


       In this post i am going to discuss about the Exception In Initialize Error.This java exception belongs to the java.lang. package.This exception extends the Linkage Error.On seeing this exception you might have no idea about the exception as i have confused.

What is Exception In Initialize Error?

On seeing the name of the exception you may be able to guess that this exception is related to initialization of a variable.Yes of course this error is related to the initialization of a static variables.The variable may be of primitive type or user defined type.You might all have known about the static initializer of a class.
A static initializer is a block enclosed within curly braces without having any name and return type except having the keyword static as follows

static
{
//initialization of values;
}

The static initializer block is meant for initializing the static variables.

Why this ExceptionInInitializer Error is thrown?

If any error occurs during the initialization of variables inside the static initializer block of a class then this error would be thrown.Thus we have to understand that this exception is thrown ,when other exceptions arise in the static initializer block.In the error message the original cause for this exception  is also shown.

How to fix this exception?

Since this exception arises in consequence of some other exceptions that arises in the static initializer block.
We have to ensure that the original cause of this exception is fixed otherwise we cannot be able to deal with this exception in any way.

Example situations of this exception:

import java.io.*;
import java.lang.*;

class Exin
{
private static String name;
private static char c;
public Exin(String n)
{
name=n;
}
static
{
c=name.charAt(12);
}
}

public class Exin1
{
public static void main(String args[])
{
Exin e=new Exin("ganesh");

}
}


Exception thrown:


Exception in thread "main" java.lang.ExceptionInInitializerError
        at Exin1.main(Exin1.java:22)
Caused by: java.lang.NullPointerException
        at Exin.(Exin1.java:14)
        ... 1 more

Note that in the above program i have tried to access the 12th character in the string "ganesh" using the method charAt() which causes null pointer exception thereby causing the ExceptionInInitializer error.

java.lang.classcastexception

ClassCastException:

      The java.lang.ClassCastException is one of the common exception that is experienced by beginners.Let us know in detail what does it mean?, When it is thrown?and how to fix this exception in this post.

What is meant by java.lang.classcastexception?

You might all be familiar with the word Cast in the programming context.In most of the programming languages Cast refers to conversion.In this exception is is given that Class Cast Exception.So it indicates  that in our program we have tried to "convert an object of one class type in to an object  of another class type".

Note:

There is one possibility in casting an object,"If a class extends a parent class then the child class object can be casted to its parent class".The reverse process is not possible in most of the programming languages.

Look at the following snippet to understand it:

Class Parent
{
..........
...........
}
Class Child extends Parent
{
...........................
}

Class Sample
{
......
Child c=new Child();
Parent p=c;                //converting an object of child type to its parent type
}

In this sample program i have tried to cast an object of class Child to its Parent class type.This is a legitimate casting.

But the reverse casting is not allowed that is

Child c=new Child();
Parent p=new Parent();
c=p; // casting an object of parent type to its child type which is not allowed


When will be this exception is thrown?

There are two main occasions on which this exception will be thrown.

1.As i have already told when you try to cast an object of Parent class to its Child class type this exception will be thrown.

2.When you try to cast an object of one class into another class type that have not extended the other class or they don't have any relationship between them.

See the example,

Class A                        
{
}

Class B
{
}

B bobject=new B();
A aobject=new A();

aobject=(A)bobject; //throws an ClassCastException

Reason: Trying to cast an object of class B to the type A.

Examples like trying to cast an String object into an Integer will throw this classcastexception.

Example Situation for this exception:

import java.util.*;
import java.io.*;

class Parent
{
String name;
Parent(String n)
{
name=n;
}
public void  display()
{
System.out.println(name);
}
}
class Child extends Parent
{
String cname;
Child(String name)
{
super(name);
cname=name;
}

public void display()
{
System.out.println(cname);
}

}

class Sample1
{
public static void main(String args[])
{
Child c=new Child("hello");
Parent p=new Parent("hai");
p=c;
p.display();
Parent p1=new Parent("world");
Child c1=(Child)p1;
}
}

output:

hello
Exception in thread "main" java.lang.ClassCastException: Parent cannot be cast t
o Child
        at Sample1.main(Sample1.java:42)

As you see the output of this program we can able to understand that i have tried to cast an object of Parent class to its Child class  type.


Example 2:

import java.util.*;
import java.lang.*;

class Listimpl{
public Listimpl(T a)
{
i=(List)a;
i.get(0).intValue();
}
private List i;
}

class Castimpl
{
public static void main(final String[] args)
{
  List s = new LinkedList();
s.add("jesus");
Listimpl i = new Listimpl(s);

}
}



This kind of exceptions also arises when we are dealing with Generic Programming.Look at the above program to understand this problem.

In the above program, I have anticipated for the List of Integer type in the constructor Listimpl but actually i have created the object for Listimpl as String type.

Since i have used List as the cast type(i=List(a);) the compiler would not bother about the type of the List that we are assigning to the List i of Integer type.

So it does not shows any compilation error while assigning to an list of Integer object type.

As the value stored in that list is a string object, when we try to convert it into an integer value using the intValue() method, class cast exception is thrown.

This kind of exceptions usually occur in the situations like,we may be anticipating an integer object from the client system but we actually received the String object,we may expect integer values as the result of a query from the database but the actual value stored in the database may be a String value.

Solution:

So,when trying to cast an object of one class type into another class type ensure that the type to be casted is of its parent type.

I hope this may avoid this classcastexception to be thrown...



How to handle java.io.notserializableexception: containing a non serializable object

          In this post i am going to deal with the object not serializable exception thrown because of containing a non-serializable object.This is another important reason for this exception to be thrown. i have already dealt with this exception thrown because of not implementing the serializable interface.


For the other post,go to the link mentioned below: 

 

What is meant by a non-serializable object?  


An object of a class that does not implement the serializable interface is called a non-serializable object. For example, you could have created an object for a class that does not implement the serializable interface,like


class Sample // A class not implementing the serializable interface
{
......

.........
}



Sample sampleobject=new Sample(); //Here 'sampleobject' is a non-serializable object.There are certain classes exists in the JDK library which cannot be serialized by default.

-->

 

When this exception is thrown?

If a class that implements the serializable interface contains statements that refers to an non-serializable object,then the  object of that class becomes non-serializable even though it implements the Serializable() interface and if you try to serialize the object then  this exception will be thrown.

 

How to fix this exception?

One solution that i suggest you is to  make the non-serializable object into a serializable one by making the class of the non-serializable object to implement the Serializable() interace or remove the reference to that object.

 

Example situations for this exception to be thrown:


import java.io.*;
import java.util.*;
class Parent
{

Parent()

{

}

String parentname;

Parent(String name)
{
parentname=name;
}
}

class Child1 extends Parent implements Serializable
{

Otherchild oc=null;

Child1(String name)
{
super(name);
oc=new Otherchild(name);// Containing(or creating) an isntance of a class "Otherchild" 
                                                                       that do not  implements the Serializable interface 
}
}


class Child2
{
public static void main(String args[])
{
Child1 c1=new Child1("ganesh");//trying to serialize the object of Child1 class
try
{

          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
          out.writeObject(c1);
          out.close();

          ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
          Parent parent = (Child1) in.readObject();
          in.close();

}

catch (Exception e)
{
e.printStackTrace();
}
}
}

class Otherchild
{
String oname;

Otherchild(String name)
{
oname=name;
}

public String getname()
{
return oname;
}
}

Exception thrown:

java.io.NotSerializableException: Otherchild

        at java.io.ObjectOutputStream.writeObject0(Unknown Source)

        at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)

        at java.io.ObjectOutputStream.writeSerialData(Unknown Source)

        at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)

        at java.io.ObjectOutputStream.writeObject0(Unknown Source)

        at java.io.ObjectOutputStream.writeObject(Unknown Source)

        at Child2.main(Child2.java:38)



In the above program i have tried to serialize the "object c1 of the class Child1 which implements the Serializable interface". But unfortunately I got the java.io.Not Serializable Exception.

Later i found that this exception is thrown because the class Child1 contains a statement that refers to an non-serializable object like this,

oc=new Otherchild(name);// Containing(or creating) an isntance of a class "Otherchild" 
                                                                       that do not  implements the Serializable interface 



This exception can be avoided by  making the non-serializable object into a serializable  object. Here,

Serializable Object -----> c1 of class Child1. 
Non-Serializable Object --------> oc of class Otherchild.


java.io.notserializableexception

Not Serializable Exception:

The java.io.notserializable exception  is one of the common exception experienced by the java programmers who uses object serialization and de-serialization concepts.In this post let us discuss about the object not serializable exception.

What is meant by java.io.notserializableException:


This exception indicates that the object that you are trying to serialize is not serializable for some reasons.This exception belongs to java.io.package.This exception is thrown while serialization of objects are performed. Let us see the two important reason for which this exception is thrown.

When this notserializable Exception is thrown?

As i have told before there are two important reason for which this exception is thrown. Let us consider first and  the most important  reason for which this exception is thrown.

The first reason for which an object becomes not serializable is that  the class of the object do not implements the serializable interface.

Conditions:


It should be noted that if we want to serialize an object of class then that class must implement the serializable  interface or it must extend the class which implements the serializable interface.

If the above mentioned conditions are not met then the objects cannot be serialized.

How to fix the not serializable exception?


1. Make the class of the object which you are trying to serialize to implement the Serializable() interface.

2.Otherwise extend the class which implements the Serializable() interface.

Example situation for this exception:


import java.io.*;
import java.util.*;
class Parent
{
Parent()
{
}
String parentname;
Parent(String name)
{
parentname=name;
}
}

class Child1 extends Parent implements Serializable
{
Child1(String name)
{
super(name);
}
}

class Child2
{
public static void main(String args[])
{
Child1 c1=new Child1("ganesh");
Parent p=new Parent("Jesus");
try
        {

          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
           out.writeObject(c1);
           out.writeObject(p);
           out.close();

            ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
           Parent pa=(Parent)in.readObject();
           Parent parent = (Child1) in.readObject();
           in.close();

        }
        catch (Exception e)
        {
           e.printStackTrace();
       }
}
}

Exception thrown:

java.io.NotSerializableException: Parent
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at Child2.main(Child2.java:35)

This Exceptions shows that i have tried to serialize the instance of the Parent class which does not implements the serializable interface in the class Child2.

 I have highlighted the statements which causes this Exceptions in Bold in the program.

Note that the class Parent does not implements the serializable interface which is the sole reason this exception.This exception can be avoided by making the class Parent to implement the Serializable interface.

I have dealt with the java.io.NotSerializableException  thrown because of  a serializable object containing a non-serializable object in the other post java.io.NotSerializableException : containing a non-serializable .


java.io.InvalidClassException: no valid constructor

Invalid Class Exception: no valid constructor

The Invalid class exception is one of the commonly experienced exception by the java programmers who use object serialization in their program.There are three main causes for this exception to be thrown.They are,
1.serial version of the class
2.containing unknown data types,
3.no-arg constructor.
In this post we will discuss about the third reason "No-arg constructor".How the absence of a no-arg constructor causes this exception to be thrown.

What is meant by Invalid class exception?

As the name of the exception indicates that, the class of the object which is serialized or deserialized becomes invalid due to one of the  reasons which i have listed out before.This causes the class to be
invalid and the objects of which cannot be serialized or deserialized.This class extends the ObjectStreamException.


When this InvalidClassException:no valid constructor is thrown?

 This type of exception is thrown when inheritance is involved in the program.When inheritance is involved, the serialization process proceeds by serializing the objects of  child classes first and then moves up the hierarchy until the non-serializable parent class is reached.

When the objects are to be deserialized it starts from the non-serializable  parent class and moves down the hierarchy.Since the parent class is non-serializable the state information about the members of the  parent class can only be retrieved from the default constructor as it cannot be retrieved from the stream.Since this state information is available only in the default constructor the absence of which makes the class invalid.

Example of the InvalidClassException:

 import java.io.*;
import java.util.*;
class Parent                      //non-serializable parent class
{
String parentname;          
                                    //absence of no-arg constructor
Parent(String name)
{
parentname=name;
}
}

class Child1 extends Parent implements Serializable
{
Child1(String name)
{
super(name);
}
}

class Child2
{
public static void main(String args[])
{
Child1 c1=new Child1("ganesh");
try
        {

          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
           out.writeObject(c1);
           out.close();


           ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
           Parent p = (Child1) in.readObject();
           in.close();

        }
        catch (Exception e)
        {
           e.printStackTrace();
       }
}
}

Output:

java.io.InvalidClassException: Child1; Child1; no valid constructor
        at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
        at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at Child2.main(Child2.java:34)


In the above program i have implemented a parent class Parent which is extended by a child class Child1. As i have told before the objects of class Child1 are serialized. When de-serializing it searches for default constructor in the parent class Parent as it is not present, this exception will be thrown.

Solution:

Include the no-arg constructor in the Parent class as follows:

Parent()
{
}




java.io.invalidclassexception: local class incompatible

Invalid Class Exception:Local class incompatible

    This exception is thrown when the serial version of the class is found to be different from  that of the class descriptor read from the stream.

Whenever object serialization is performed the objects are saved in a particular file format.This file format contains a class descriptor for each class of the object that is saved.

The class descriptor usually contains the 
  • class name
  • serial version unique ID
  • set of flags
  • description of the data fields
If the value of the serial version unique Id  is not explicitly specified then the jvm will automatically assigns the value for this variable.

We can also be able to assign value for this variable like 1L or 2L.

One thing should be importantly noted that the serial version unique Id should  be same during object serialization and deserialization.

 During serialization this serial version unique Id value would be recorded in the class descriptor.

While deserialization current serial version unique Id value would be compared with the one in the class descriptor.If there is any mismatch between the values this exception would be thrown.

I have also included the example program of object serialization and indeed i have changed the serial version unique Id value during deserialization.

Program:

Invalid.java

import java.io.*;
import java.util.*;
public class Invalid implements Serializable
{
public static final long serialVersionUID =2L;

String empname;
int empno;

public Invalid(String name,int no)
{
empname=name;
empno=no;
}
public String getname()
{
return empname;
}
public int getno()
{
return empno;
}
}

Writeobject:


import java.io.*;
import java.util.*;
public class Writeobject
{

public static void main(String args[])
{

Invalid iv=new Invalid("shaun",10);
 try
   {

            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));
            System.out.println(iv.getname()+iv.getno());
            out.writeObject(iv);
            out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Readobject:


import java.io.*;
import java.util.*;
public class Readobject
{

public static void main(String args[])
{
Invalid inv=null;
 try
   {

         ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));
           inv = (Invalid) in.readObject();
           in.close();
           System.out.println(inv.getname()+inv.getno());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output:

C:\>cd manet

C:\manet>javac Invalid.java

C:\manet>javac Writeobject.java

C:\manet>java Writeobject

shaun10

C:\manet>javac Readobject.java

C:\manet>java Readobject

shaun10

C:\manet>javac Invalid.java

C:\manet>javac Readobject.java

C:\manet>java Readobject

java.io.InvalidClassException: Invalid; local class incompatible: stream classde

sc serialVersionUID = 1, local class serialVersionUID = 2

        at java.io.ObjectStreamClass.initNonProxy(Unknown Source)

        at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)

        at java.io.ObjectInputStream.readClassDesc(Unknown Source)

        at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

        at java.io.ObjectInputStream.readObject0(Unknown Source)

        at java.io.ObjectInputStream.readObject(Unknown Source)

        at Readobject.main(Readobject.java:13)


Note that  when executing the above programs for the second time i have purposefully changed the Serial Version Unique Id  to 1L while reading the objects(de-serializing).Because of this invalid class Exception is thrown.

java.io.interruptedioexception

InterruptedIOException:

  • The Interrupted IOException is thrown when the input or output transfer has been terminated because the thread performing it was interrupted.Simply it shows us that the I/O transfer has been interrupted.
  • This type of exceptions usually occur in the network programming wherein the client tries to communicate with the server.
  • If the host is unreachable the client/Server waits for a long time and you are at the mercy of the underlying operating system to time out eventually.
  • Rather than waiting for a long time to timeout,you can also be able to interrupt the thread by using the InterruptedIOException,thereby terminating the socket connection.
  • For this purpose a method called setSoTimeout() is provided in which you can specify the value of the timeout.
  • If the waiting time exceeds the timeout value then the InterruptedIOException is thrown to indicate the sockect connection termination.

Program:

import java.io.*;
import java.net.*;
public class Server{
ServerSocket SSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Server(){}
void run()
{
try{

SSocket = new ServerSocket(5000, 10);
SSocket.setSoTimeout(10000);
System.out.println("Waiting for connection");
connection = SSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
         out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
out.writeObject("Connection successful");

do{
try{
message = (String)in.readObject();
System.out.println("client>" + message);
if (message.equals("done"))
out.writeObject("done");
}
catch(ClassNotFoundException c)
{
c.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}while(!message.equals("done"));
}
catch(InterruptedIOException e)
{
System.out.println("InterruptedIOException");
e.printStackTrace();
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
try{
in.close();
out.close();
SSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}

public static void main(String args[])
{
Server server = new Server();
while(true){
server.run();
}
}
}

The above program shown is an example of socket connection.This program acts as a server and it has a timeout value set for 10 seconds.If any client fails to communicate to the server within 10 seconds then InterruptedIOException will be thrown.This Exception will be more useful in client side.

Error:

Waiting for connection
InterruptedIOException
java.net.SocketTimeoutException: Accept timed out
        at java.net.PlainSocketImpl.socketAccept(Native Method)
        at java.net.PlainSocketImpl.accept(Unknown Source)
        at java.net.ServerSocket.implAccept(Unknown Source)
        at java.net.ServerSocket.accept(Unknown Source)
        at Server.run(Server.java:17)
        at Server.main(Server.java:65)
Exception in thread "main" java.lang.NullPointerException
        at Server.run(Server.java:51)
        at Server.main(Server.java:65)
The temp batch file is supposed to be deleted hence...
The batch file cannot be found.

Process returned 0 (0x0)   execution time : 10.177 s
Press any key to continue.


how to create a batch file using java


Batch File:

  • In this post i am going to show you the implementation of java program to create a batch file.
  • We might all wonder about "what is a batch file?","what a batch file contains?". The batch file contains only the DOS commands which we would type in the command prompt.
  • If you have seen any application,the installation package of the software may contain one or more batch files.These batch files are designed to perform the predefined tasks in the background.     
  • We can able to configure the batch file on our own to perform the tasks that we want to do.
  • For eg. Initially,when we start to learn java we used the command prompt to compile and execute our program.Before compilation we may have to configure some settings like setting the class path,path etc.
  • These type of settings can be easily configured by using the batch file rather than typing the commands manually.  
The java code for creating the batch file is shown below.

Program:

import java.io.*;
import java.util.*;
import java.lang.*;

public class Bat
{

public Bat()
{
}
public static void main(String args[]) throws Exception
{
Batch b=new Batch();
b.createBat();
b.executeBat();
}
}


import java.io.*;
import java.util.*;
import java.lang.*;

public class Batch
{
public Batch()
{
}
public void createBat() throws Exception
{
File file=new File("C:\\manet\\Execute.bat");
fos=new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeBytes("CD \\");
dos.writeBytes("\n");
dos.writeBytes("CD Project Document");
dos.writeBytes("\n");
dos.writeBytes("SET CLASSPATH=c:\\Program Files\\Weka-3-7\\weka.jar;");
dos.writeBytes("\n");
dos.writeBytes("cd ..");
dos.writeBytes("\n");
dos.writeBytes("ECHO $GANESH");
dos.writeBytes("\n");
dos.writeBytes("CD \\ ");
}

public void executeBat() throws Exception
{
String cmd="cmd /c start c:\\manet\\Execute.bat";
Runtime r=Runtime.getRuntime();
Process pr=r.exec(cmd);
}
FileOutputStream fos;
DataOutputStream dos;
}

The above program will create a batch file named "Execute.bat" and it will start reading the contents of the file as commands and execute it in the console(command prompt).

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException


ArrayIndexOutOfBoundsException:


The ArrayIndexOutOfBounds Exception is common in the java program that uses array for storing the values.There are many exceptions associated with the arrays like ArrayStorageException and ArrayIndexOutOfBounds Exception.Let us discuss about the ArrayIndexOutOf Bounds Exception.

What is meant by ArrayIndexOutOfBoundsException?

The ArrayIndexOutOf Bounds Exception  message gives us some knowledge about this exception.This exception message indicates that a particular statement in the program tries to access the value in the index(Position number of the particular value in the array) which is either greater than or negative or equal to the size of the index.

For eg) Let String a[]={"a","b","c"};

Here a[0]=a;
         a[1]=b;
         a[2]=c;

Here 1,2,3.. represents the index value.

Briefly said ,it shows us that we are trying to access the index position which is either greater or negative to the size of the array.

When will be this exception is thrown?

As i have said before ,the only reason for this exception to be thrown is: using the index(position) greater than or negative to the size of the array.For eg.If the size of the array is 4 and we are trying to access the value at index 5 will cause this exception to be thrown.

How to Fix this Exception?

In many occasions you might think of increasing the size of the array to mitigate this exception.But this is not the desired solution.If your programming logic is not correct then even if you increase the size of the array this exception will be thrown.So try to correct the statement that causes this exception.So while dealing with arrays ensure that your statement tries to access the value only within in the size of the array.

Example situation of this exception:

public class Desc
{
public static void main(String args[])
{
int t;
int a[]={2,7,4,5,6};
for(int j=0;j<5;j++)
{
for(int i=j+1;i<=5;i++)
{
if(a[j]<a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(int h=0;h<5;h++)
System.out.println(a[h]);
}
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at Desc.main(Desc.java:11)

In the above code,line no 11.for(int i=j+1;i<=5;i++) contains a statement which tries to access the index equal to the size of the array.So this statement causes an ArrayIndexOutOfBoundsException

Errorjava.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

        In this post i am going to tell you all about the most commonly found Exception:- Data source not found and no default driver specified.This is one of the sql Exception which would be thrown when the jdbc:odbc connection is not performed correctly.First of all we must know about the two important things in any database connection

 Data source name:


 Data source name is nothing but the database name in which u would create tables to
 store the data.

Default Drivers:


There are many drivers available in your computer for making jdbc:odbc connection each for specific database.For eg Microsoft Access Driver for creating a connection with the MS Access database.Similarly for sql,mysql and sybase.

This error would occur when creating a jdbc:odbc connection for MS Access database.when i am doing a simple mini-project which makes use of  MS Access for back-end support i encountered this error.

Here is the part of the project code which involves making a database connection

Program:

 

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class Dem extends JFrame
{
public Dem()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(false);
this.setSize(400,400);
this.setTitle("ADDRESS BOOK");
bp1=new JPanel();
bp2=new JPanel();
bp1.setLayout(new GridLayout(4,4));
label1=new JLabel("NAME");
text1=new JTextField(25);
bp1.add(label1);
bp1.add(text1);
label2=new JLabel("ADDRESS");
bp1.add(label2);
text2=new JTextField(25);
bp1.add(text2);
label3=new JLabel("SEX");
bp1.add(label3);
text3=new JTextField(25);
bp1.add(text3);
label4=new JLabel("PHONE NO");
bp1.add(label4);
text4=new JTextField(25);
bp1.add(text4);
JButton back=new JButton("BACK");
bp2.add(back);
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
setVisible(false);
}
});
//To create database
create();

JButton submit=new JButton("SUBMIT");
bp2.add(submit);
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e1)
{
insert();
}
});
JButton reset=new JButton("RESET");
reset.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e7)
{
text1.setText("");
text2.setText("");
text3.setText("");
text4.setText("");
}
});
bp2.add(reset);
add(bp1,BorderLayout.NORTH);
add(bp2,BorderLayout.SOUTH);
}
public void create() 
{
try
{

//Creating the database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dsn="prodb21";
String url="jdbc:odbc:"+dsn;
Connection con=DriverManager.getConnection(url,"","");
try
{
Statement s=con.createStatement();
s.execute("create table prod21(name varchar(20),address varchar(20),sex varchar(10),phno varchar(12))");
s.close();
}
finally
{
con.close();
}
}
catch(Exception err)
{
System.out.println("Error"+err);
}
}
public void insert()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:prodb21");
try
{
PreparedStatement pstm=con.prepareStatement("insert into prod21 values(?,?,?,?)");
pstm.setString(1,text1.getText());
pstm.setString(2,text2.getText());
pstm.setString(3,text3.getText());
pstm.setString(4,text4.getText());
pstm.executeUpdate();
}
finally
{
con.close();
}
}
catch(Exception err1)
{
System.out.println("error"+err1);
}
}
 JPanel bp1,bp2;
JLabel label1,label2,label3,label4;
JTextField text1,text2,text3,text4;
}



In the above program,under the comment line Creating the database connection,i have used the data source name as Prodb21 and the table name as prod21. Lets see how i created the database connection for this part of the program. 

 

Creating a jdbc:odbc Connection:


1) Go to control panel and choose System Security->Administrative tools or simply search in the search toolbar in the control panel for the keyword ODBC.

2) In that Administrative tools window select Data Sources(ODBC).

3) Then ODBC data source administrator window will appear.In that select System DSN tab
On the right side of the window there will be a ADD button.Click it to add a driver for this database connection,then create new source window will appear.

4) In that window select Microsoft Access Window(*.mdb) and click Finish.

5) Then ODBC Microsoft Access Setup window will appear.Give the database name in the data source name field and click create.

6) In the next window select the location for the database and give the database name once again in the top left corner field and click ok.

7) Then a window will prompt a message "database is successfully created".Here few things are to be noted down.Keep the database in the same location as the program resides.

8) These above mentioned steps will create a jdbc:odbc Connection successfully.




java error 1722


Error 1722 in java

Error 1722: There is a problem with this windows installer package. A program run as part of the setup did not finish as expected.Contact your support personnel or package vendor.

This error is an install shield error code.This indicates that the installation process has failed.

One way that resolves this problem is uninstalling the corrupted java package. This can be done as follows:




    • Remove  all the traces of Java Runtime from your computer. Do this by clicking the Windows "Start" button and clicking the "Control Panel."
  • Double-click "Add or Remove Programs" (Windows Vista users) to open the programs window. For Windows Vista users, click "Program and Features" and click "Uninstall a Program" to open the programs window.
  • Scroll through the Programs window and select the Java application you have and click "Remove/Uninstall" to remove it from your computer.
    •     Try downloading and installing Java (see Resources) again. Move to the next step if you run into the 1722 error again.
  • Download the offline Java installation file (see Resources) and save it on your desktop. Double-click the offline installation file and click "Run" to begin the installation wizard.
    • Click "View license agreement." Click "Install" after reading it. The files are copied to your computer system and the program is installed on your computer.

    • Even if the error is not resolved,then we have to remove the register entries for this corrupted java installation manually.


    • Follow those steps to resolve this problem.


 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top