Add to Google Reader or Homepage

java.io.UnsupportedEncodingException

UnsupportedEncodingException:


"An UnsupportedEncodingException will be thrown only if the given Charset is not Supported by your JVM".

There are some particular set of "Charsets"  that are supported by your JVM. If the given charset is not in that list then it is certain that this error will be thrown.

So first check whether the given Charset is supported by your JVM.If you have no idea about the available character sets, Use the following code to list the available charsets.


Map csets = Charset.availableCharsets();
for (String name : csets.keySet())
   System.out.println(name);

See the following program which i have simulated,that causes this error.

Program:

import java.io.*;
import java.util.*;
import java.nio.charset.*;
class Unsuppencode
{
public static void main(String args[])throws Exception
{
ByteArrayOutputStream byteout=new ByteArrayOutputStream(10);
byteout.write(10);
String s=byteout.toString("IBM859");
Map csets = Charset.availableCharsets();
for (String name : csets.keySet())
   System.out.println(name);

}
}


As you see there is no such charset named IBM859 in the JVM thus causing this unsupported encoding exception.So when using a particular charset check whether it is supported(available) by your JVM.

2 reasons for java.io.OptionalDataException

OptionalDataException:

 

This java.io.OptionalDataException is usually thrown when we try to deserialize an object
from the stream. Let's see in this post what are the reasons for this exception to be thrown while deserializing an object.

There are two reasons for this exception to be thrown.They are

1.When we try to deserialize a primitive type(like int,string,char,float,double) using the readObject() method of the DataInput interface then this exception will be thrown.

2.When we try to deserialize an object which is no longer available in the stream using the custom readObject() method(which is the class-defined readObject() method).

Here in this post i have presented you two examples which explains you why this exception is thrown because of this two reasons.

Reason1:

 

"Deserializing a primitive type data"

Have a look at the following program and its output to understand why this exception is thrown because of this reason.

Program:

Students.java:

import java.util.*;
import java.io.*;
class Students implements Serializable
{
String name;
int Regno;
}

 
Optional.java:

import java.io.*;
import java.lang.*;
import java.util.*;
class Optional extends Students
{
public static void main(String args[])
{
try
{
Optional op1=new Optional();
op1.name="Ganesh";
op1.Regno=80;
Optional op2=new Optional();
op2.name="Hari";
op2.Regno=90;
int a=10;
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("serial.dat"));
os.writeObject(op1);
os.writeInt(a);

os.writeObject(op2);

ObjectInputStream is=new ObjectInputStream(new FileInputStream("serial.dat"));
Optional p=(Optional)is.readObject();
Optional s=(Optional)is.readObject();

System.out.println(s.name);
System.out.println(s.Regno);
System.out.println(p.name);
System.out.println(p.Regno);

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

Output:

 

 java.io.OptionalDataException
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at Optional.main(Optional.java:24)
The temp batch file is supposed to be deleted hence...
The batch file cannot be found.
Process returned 0 (0x0)   execution time : 0.243 s
Press any key to continue.

 

If you look at the highlighted statements in the above program,you can able to infer that. First i have stored an object op1  of Optional type in the stream and then i stored the primitive type(int a) in the stream.

But while deserializing the objects, I tried to deserialize both the objects as of type (Optional) Since the second object is of int (primitive) type this OptionalDataException is thrown. If you try the reverse case i.e, deserializing both the objects as of primitive type then EOF file exception will be thrown.

Here you have to remember one thing that "you should deserialize the objects in the same order in which you have serialized the object".

Reason 2:

 

"Trying to read the unavailable object from the stream using the custom class-defined readObject() method".

Look at the program below to understand how i have used the custom readObject() method  to deserialize the objects from the stream.

Program:

Ram.java

import java.io.*;
class Ram implements Serializable
{
String name;
int mark;
}
 

Serialize.java

class Serialize
{
public static void main(String args[])
{
Primit p=new Primit();
p.execute();
}
}


Primit.java

import java.io.*;
import java.util.*;
import java.lang.*;
class Primit implements Serializable
{
Ram r=new Ram();
Ram r1=new Ram();
Ram r2=new Ram();

public void execute()
{

try
{
r.name="ram";
r.mark=90;
r1.name="ram1";
r1.mark=80;
r2.name="ram2";
r2.mark=70;
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("primit.dat"));
os.writeObject(this);
ObjectInputStream is=new ObjectInputStream(new FileInputStream("primit.dat"));
is.readObject();
}
catch(Exception e)
{
e.printStackTrace();
}
}

private void writeObject(ObjectOutputStream out)throws IOException
{
System.out.println("I am inside writeObject()");
out.defaultWriteObject();
out.writeObject(r);//
Object no:1
out.writeObject(r1);// Object no:2
out.writeObject(r2);// Object no:3
}

private void readObject(ObjectInputStream in)throws IOException,ClassNotFoundException
{
System.out.println("I am inside readObject()");
in.defaultReadObject();
Ram s=(Ram)in.readObject();//
Object no:1
System.out.println(s.name);
Ram s1=(Ram)in.readObject();//
Object no:2
System.out.println(s1.name);
Ram s2=(Ram)in.readObject();//
Object no:3
System.out.println(s2.name);
Ram s3=(Ram)in.readObject();//
Object no:4
}
}

Output:

I am inside writeObject()
I am inside readObject()
ram
ram1
ram2
java.io.OptionalDataException
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at Primit.readObject(Primit.java:50)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
        at java.io.ObjectInputStream.readSerialData(Unknown Source)
        at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at Primit.execute(Primit.java:24)
        at Serialize.main(Serialize.java:6)



If you look at the highlighted statements in the above program you can able to infer one thing that i have serialized  only three objects but  i have tried to deserialize Four objects.Since the fourth object is not available in the stream this exception is thrown at run-time.


3 reasons for java.lang.verfiyerror

VerifyError:

It is an other sub class of  IncompatibleClassChangeError which is thrown at run-time due to binary incompatibility.If you would like to know what is meant by binary incompatibility, refer to my older post java.lang.IncompatibleClassChangeError.In this post i have explained three reasons upon which this Verify Error is thrown.

Before explaining this error,i would like to tell you something about how a java program gets executed.When ever we compile a program,the byte codes are formed.Before executing these byte codes,they are preprocessed by a ByteCodeVerifier.The ByteCode Verfier examines the byte codes,to check  is there any statement that violates the semantics of java.If any such statements are found then this verify error will be thrown.

Here i have presented you three reasons upon which this error may occur as follows.

Reason 1:

"Whenever we try to extend a class which is declared as final then this error will be thrown". Have a look at the following program to understand this reason.

Program:

class B extends A
{
public static void main(String args[])
{
System.out.println("my super class name:-"+myname);
}

 public class A
{
static String myname="A";
}

As you see if you compile this two programs and execute it,it must have to work fine without showing any error. Now I am going to change the class A  as follows and compile it alone. Note that here i have recompiled the "class A" alone.Now if i execute the class B (class that contains main() method) then an error message like below will be thrown at run-time.


final public class A
{
static String myname="A";
}


 Exception in thread "main" java.lang.VerifyError: Cannot inherit from final clas
s
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: B.  Program will exit.

Reason 2:


 "Consider a class that extends an other class before and if it no longer extends that class now,then this error may be thrown at run-time."Look at the following program to see how the second reason causes this error.


 Program:

class C extends B
{
public static void main(String args[])
{
B b=new B();
display(b);
}
public static void display(A a)
{
System.out.println(a.supername);
}
}


class B extends A
{
String subname="B";
}


 public class A
{
String supername="A";
}

 The above program will also works fine,but if i change the class B to no longer extend the class A then this error may get thrown.Now if i change the class B as follows,and "recompile it alone" ,then class C will have no idea about the changes made in class B thus causing this error.

class B
{
String subname="B";
}


Exception in thread "main" java.lang.VerifyError: (class: C, method: main signat
ure: ([Ljava/lang/String;)V) Incompatible argument to function
Could not find the main class: C.  Program will exit.

Reason 3:

"If we try to override a method which is declared as final then also this error will be thrown". Let us have classes A and B as follows:

Program:


class B extends A
{
public static void main(String args[])
{
A a=new A();
a.display();
}
void display()
{
super.display();
}
}

 public class A
{
String supername="A";
void display()
{
System.out.println("My name is"+supername);
}
}

In the class A if i change the method display() to be of final and "recompile it alone", then this verify error will be thrown if i execute the class B since  no other class can override this method.

output:

Exception in thread "main" java.lang.VerifyError: class B overrides final method
 display.()V
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: B.  Program will exit.

Here you could have noticed that this Verify Error is thrown because " i have recompiled only the edited class" and not all the classes as a whole. So you may think that this error can be easily identified if you recompile all the classes as a whole by recompiling the class which contains the main() method.

Of course it is true but there are certain situations at which you cannot be able to identify this error at Compile time,which is mainly because of using two different version of  third-party libraries in your application. 

I have presented you an example to show you how this error occurs when we use third-party libraries in your system in my older post  java.lang.illegalaccesserror .


java.lang.illegalaccesserror

IllegalAccessError:

This java.lang.illegalAccessError is thrown when we try to access a private field,class or method.Usually this error is caught by compiler.If this error is thrown at run-rime then the class must be incompatibly changed.This is the reason why this error is a direct subclass of IncomaptibleClassChangeError.

This error commonly occurs when we use third-party libraries (external packages) in our application. Normally using  an external library in your application does not cause any error if it is compatible with the existing classes (more precisely existing binaries of those classes).

If it is incompatible with the existing binaries then an instance of sub class of IncompatibleClassChange Error will be thrown and specifically an instance of illegalAccessError will be thrown when we try to access a private field,method,class or interface.

See the following examples to have an idea about this error.

Program:

class C
{
static int c=20;
public void display(String a)
{
System.out.println(a);
}
}

class D extends C
{
public static void main(String args[])
{
c=45;
System.out.println(c);
C cobj=new C();
System.out.println(cobj.c);
cobj.display("Hello");
}
}

Let us analyze this program in detail to understand when this error will be thrown.If you compile and execute this program it will work fine.But if you change any field or method in class C to private and "recompile the class C alone" without recompiling all the classes at one shot then you will be left in a   awkward situation.

Note:

One thing i forgot to mention before is that this error will also occur when we try to modify the value of the field which is declared to be final.
So, it seems obvious that after all  this error is thrown  because of not recompiling the class files as a whole.Now,in order to find this error at compile-time you have to recompile all the class files at one shot.But at some occasions this error will not be identified even if you recompile all the classes and the reason is due to the availability of  two-different version of the package in the system.


Before explaining further i would like to tell you one thing that some peoples tends to place their  external packages(third-party libraries-usually an archive file) in the extension libraries and also in bootstrap libraries to avoid class path settings.

The remaining of this post is meant for those peoples Who may "accidentally" do like as follows?

Have a look at what am i going to do here? Here i have created three different version(1 original version as described above and two new Versions) of the class C as follows;

Version 1:

class C
{
private static int c=20;
private void display(String a)
{
System.out.println(a);
}
}
 

Here i have changed the access modifier of field c (static int c=20) and method display() into private.

Version2:

class C
{
final static int c=20;
public void display(String a)
{
System.out.println(a);
}
}

Here i have changed the type of field c into final.

Now i am going to pack these three different versions into three different jar files like pack1(original version),pack2(version 1),pack3 (version 2).

C:\blog>jar -cvf Pack1.jar C.class
added manifest
adding: C.class(in = 448) (out= 301)(deflated 32%)

C:\blog>jar -cvf Pack2.jar C.class
added manifest
adding: C.class(in = 448) (out= 300)(deflated 33%)

C:\blog>jar -cvf Pack3.jar C.class
added manifest
adding: C.class(in = 412) (out= 291)(deflated 29%)

Now if i place the Pack1.jar in jre/lib/ext and the Pack2.jar file in class path then while compiling the source file compiler will resolve the references using Pack1.jar since it is available in the extension library itself and as soon as the class file is found compiler will stop searching for classes further in class path.

During the launching of the applicationJVM also tends to search for class file in the class path as the reference in the archive file(located in the extension library) cannot be found by the JVM,because JVM only looks in jars that are"extensions of the java platform" and it will not search in user generated jars or third-party libraries.

So in this case JVM has no choice and it has to make use of the available reference (class C) in the Version 1  of the package that is pointed by class path.This is the reason why compiler does not show any error and the JVM shows this error during run-time.

Output:


C:\>cd blog

C:\blog>set classpath=c:\blog\Pack2.jar;c:\blog\Pack3.jar;

C:\blog>javac D.java

C:\blog>java D
Exception in thread "main" java.lang.IllegalAccessError: tried to access field C
.c from class D
        at D.main(D.java:5)





java.lang.NoSuchFieldError



NoSuchFieldError:


I guess you may all be familiar with this error,"which is thrown when we try to access a field which does not exist in the class,interface or enum".You may think if we try to access a unavailable field then at the compile-time itself you would be alerted of this error then how come this error is thrown at run-time.

In most of the cases this error is thrown when we use third-party libraries in our application and   i will explain you how in this post.

This error is thrown because of binary incompatibility,which arises when we modify a class in such a way that the class is ended up in an inconsistent state.

The main reason for this error to be thrown at run-time is "that you may have accidentally (indeed purposefully) deleted a field(public or protected) from the class, or interface and recompiled the edited class or interface alone."

As a result,pre-existing classes that has symbolic reference to this field will have no idea about the deletion of the field.So if you execute the class without recompiling it then at the run-time only you will be shown this error message.

Have a look at the following program to understand.

Class C

class C 
{
static int c=20;
}

Class D

class D extends C
{
public static void main(String args[])
{
System.out.println(c);
}
}


 This program will run without showing any error. Now If i delete the field c from class C(static int c=20) and recompile it alone then class D would not be aware of the changes made in the class C. This is the reason why java.lang.NoSuchFieldError is thrown when i execute the class D.

This error also applies to enumerated types,because if you delete the enum constant and if you try to access the constant without recompiling the class to be executed,you will get this error.See how

Program:

 import java.util.*;

 public class Nosuch
{
  public static void main(String[] args)

{

  Level l=Level.LOW;
  System.out.println(l.toString());
 }
 }



enum Level
 {
LOW,MEDIUM,HIGH;

}



 If  i delete the enum constant  "LOW " from the enum declaration and recompile the Level.java file alone and execute the class Nosuch then you will get this error.


Exception in thread "main" java.lang.NoSuchFieldError: LOW

        at Nosuch.main(Nosuch.java:7)



Thus it is obvious that if we compile the classes as a whole then at the compile-time itself you would get this error.So you can make the necessary changes to correct those errors.

An important thing to be noted here is that we people mostly would not do like this and you may ask me then when will this error be thrown?

As i have said before mostly this kind of error is thrown when we use third-party libraries (packages) in our applicationBecause we have no idea about the changes made in those libraries and if you use those library classes without recompiling the application as a whole then this error would be thrown. 

When re-compilation also becomes ineffective?

There are certain situations at which this exception will not be identified by the compiler even if you Re-compile it as a whole.If this is the case for you then you should have to check your classpath settings and most importantly extension libraries (jre/lib/ext) and bootstrap libraries which is the default location,where the compiler will look for classes when resolving references.

"If you have older version of the third-party packages in the extension libraries or in bootstrap libraries and newer version of the package in the class path then compiler will not show this error because while resolving references older version would be used since it is available in the system libraries itself (where class files are first searched)and during execution newer version might be used".

So ensure that two different versions of the same package does not exist in your class path and in the extension libraries.It is advisable to remove the older version completely from the system.





java.lang.incompatibleclasschangeerror

Incompatible class change error:


If you read the error message Incompatibleclasschangeerror,you may understand that a class had been incompatibly changed. But you may have no idea about what causes this exception to be thrown?.Here i have presented you,some simple situations at which this exception will be thrown.Lets have a look at it.

We may all know about the binary compatibility which must be preserved when we use third party libraries in our application.

Binary Compatibility- what does it mean?


Whenever we change an application(especially a class)we should ensure that the newly modified class is compatible with pre-existing binaries(class) otherwise,you would suffer from a linkage error.

I have explained three simple reason at which this exception may arouse.

Reason 1:


Lets have two classes like class A and class B as follows.

Class A:

public class A
{
int t=10;
}

Class B:

class B
{
public static void main(String args[])
{
A r=new A();
r.t=20;
}
}

output:


Exception in thread "main" java.lang.IncompatibleClassChangeError: Expected non-
static field A.t
        at B.main(B.java:6)


If you compile and execute the class B everything will work fine and you will not get any error.Now let's change the field t (int t=10) in class A into a static field and compile the class A alone. Now if you execute the class B(without recompiling it) then a java.lang. incompatibleclass change error would be thrown.

Thus if you have compiled the classes as a whole then at the compile-time itself you would be able to identify this problem.

"Note that if you change a public or protected variable from static to non-static or vice-versa then this exception will be thrown".

Reason 2:


This limitation is not only confined to variables,it is also applicable to methods as well.Thus if you try to change a public or protected non-static method into a static method or vice-versa,at 
that time also this exception will be thrown.

Class A:


public class A
{
public static void display()
{
int t=10;
}
}

Class B:


class B
{
public static void main(String args[])
{
A r=new A();
r.display();
}
}

Output:

Exception in thread "main" java.lang.IncompatibleClassChangeError: Expecting non
-static method A.display()V
        at B.main(B.java:6)

Reason 3:


Before explaining this reason i would like to remind you all about an important thing that "whenver you add a field to an interface it may hide the field inherited from the super class ".So if you declare same variable of same type in both the interface and in the super class then this incompatible error would be thrown. Look at the following example, I have used the classes A,B,C,D and an interface Incmp as follows.


Incmp:

interface Incmp
{
//C c=new C("10");
}


Class A:

public class A
{
C c=new C("ganesh");
}

Class B:

class B extends A implements Incmp
{
public void cal()
{
Object cobject=c;
c.display();
}
}

Class C:

class C
{
String c;
public C(String s)
{
c=s;
}
public void display()
{
System.out.println(c);
}
}

Class D:

class D
{
public static void main(String args[])
{
B b=new B();
b.cal();
}
}

As you see the interface Incmp  i made those those statements as comment lines and when i execute it the everything works fine.When i remove the comment lines and compile the interface alone then this error is thrown when i execute the class D.

Output:


C:\blog>javac D.java

C:\blog>java D
ganesh

C:\blog>java D
Exception in thread "main" java.lang.IncompatibleClassChangeError: Expected non-
static field B.c
        at B.cal(B.java:5)
        at D.main(D.java:6)


It may also occur at some other situations say for example,

we know that to extend a class we need to include the extends keyword,if you use implements  keyword instead of it or vice-versa then also this exception would be thrown.Though this reason looks silly,if you have accidentally done like that,then you would be facing this error.

Note:


1.Usually this kind of  awkward situation occurs when we use third-party libraries in our application, because the new version may have changed the signature of the variable or method that exists in the older package.So in order to avoid these kind of situations read the documentation of the package fully,before using it.

2.I have also encountered this error and it is not identified at compile-time even if i have compiled the classes as a whole,but it is thrown at run-time.The reason is that,while resolving symbolic references the compiler used the older version of the package and during execution JVM used the different version,since compiler and JVM has different search strategies for searching classes.

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