Add to Google Reader or Homepage

java.lang.AbstractMethodError

AbstractMethodError:


This java.lang.AbstractMethodError is usually thrown when we try to invoke the abstract method.

 we know that an abstract method cannot be invoked and if we try to do so then you will get a compile-time error.So you may think how this error is thrown at run-time?.

The reason is binary incompatibility-what does it mean?

         Whenever a class is modified,other classes that refer to this (modified) class will not be aware of the changes made in it.So all the classes must be compiled as a whole.If not then you may encounter one of the subclasses of incompatible class change error.


"This error indicates that the method that you invoke  is converted into an abstract method now".

see the following example to have an idea about this error

class B
{
public void display()
{
System.out.println("I am inside B");
}
}


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

output:



C:\blog>javac A.java

C:\blog>java A
I am inside B

Now i am going to convert the display() method as an abstract method and compile it alone. 

 abstract class B
{
public abstract void display();
}

Output:


C:\blog>javac A.java

C:\blog>java A
I am inside B

C:\blog>javac B.java

C:\blog>java A
Exception in thread "main" java.lang.AbstractMethodError: B.display()V
        at A.display(A.java:3)
        at A.main(A.java:8)



As you see,the reason for this exception to be thrown at run-time is i have not compiled the classes as a whole.So whenever you make changes to the existing classes ensure that you have compiled the classes as a whole.

Hence it is not a good practice to change a method into an abstract method in classes that are distributed.Mostly these kind of error occurs when you use third party library in your application.

If this error is not shown at compile time,even if you compile it as a whole package then you must have to check your library settings and class path settings.

Because compiler usually searches for classes in system libraries like bootstrap libraries and extension libraries,also in the current directory,but JVM searches for classes in the specified classpath.

If you accidentally placed your older version in the system libraries and the newer version in the class path then you will not be notified of this error even if you compile it as whole package.

So ensure that the settings relevant to older package has been removed.




java.lang.NoSuchMethodError

No Such Method Error:

If you have a look at the error message java.lang.NoSuchMethodError  you may understand that the Java Virtual Machine is trying to indicate us that the method you invoked is not available in the class or in an interface.


You could have also seen this error thrown when executing a class that has no public static void main() method.To know the reason behind this read this post.

When you try to invoke a method that is no longer available in a class then at the compile time itself you will be shown an error message "cannot find symbol". So you may think how come this error is thrown when launching  a program or an application.

I have explained the fact behind this issue using the following programs.

Let's have a class Nomethod and Pro1 as follows,

Nomethod class:

import java.util.*;

class Nomethod

{
public static void main(String args[])
{
Pro1 s=new Pro1();
s.display();
}
}

Pro1 class:

class Pro1
{
public void display()
{
System.out.println("I am inside display");
}
}

When you execute this program it will work fine without showing any errors.Now look at what happens when i change the  class Pro1 as follows and compile this class alone.

Example1:

class Pro1
{
}

Example2:

class Pro1
{
public int void display()
{
System.out.println("I am inside display");
return 1; // for example i have included a statement  like this
}
}

Now if you execute the class Nomethod without recompiling it then you will be embarrassed by this java.lang.NoSuchMethodError at run-time.

1. If you change the class Pro1 as  shown in Example1,then this exception will be  thrown because there is no method display() available in that class.

 2. If you consider the Example2 this error is thrown because the signature of the method display() has been changed.

If you understand this examples then you might have understood the reason for this error thrown when executing a class that has no main() method.

The real fact is that "binary compatibility with the pre-existing binaries(classes) have been compromised by the new binaries(modified classes)". 

"when you change the signature of a method or delete a method in a particular class" and compile it alone then other classes that invokes this method will have no idea about the state of the method,thus causing this error to be thrown at run-time.

The same case applies to interfaces also,"if you try to change the signature of a method  or delete a method in the interface" at that time  also this exception will be thrown.

What could be the solution for this?

"If you have recompiled the other class, that invokes this modified method or deleted method in the class or in an interface" then this error will be shown at the compile-time itself and you can do the necessary steps to resolve it.

Note:

Things may get even worse,consider a situation like even if you recompile the class you will not be indicated of this error.What will you do?...

Say,for an example you include a older version of the package in your project and you have placed it in the extension library.You also have the newer package(in which the signature of the method has been changed) and you have included that package in the class path.

When compiling the classes the compiler will search for the classes in the extension libraries and bootstrap libraries to resolve the references,but the java virtual machine searches only in the class path(for third-party libraries) that has been specified.

So when using a new package in your application,ensure that the settings relevant to the older version had been modified and read the documentation of the newer package to know the changes that has been made in this package.








java.lang.instantiationexception-revised

Instantiation Exception:



     In Java API , it is given that,when we try to create an instance of a class "which cannot be instantiated" using the newInstance() method of the class Class,then this exception will be thrown.


what classes cannot be instantiated?

       
         
If the class object represents "the abstract class or primitive types or a class that has no nullary constructor" then those classes cannot be instantiated.

"But an other interesting fact is that this exception is not only thrown when we use the newInstance() method of the class  Class ,but also thrown when we use the new Keyword."

Let's see how?


we all know that an abstract class cannot be instantiated.But if we try to instantiate an abstract class using the new keyword then at the compile-time itself you will be shown an error message that "abstract class cannot be instantiated". Then how come this exception is thrown at run-time?

At this point i am supposed to say you about binary compatibility that exists in java programming language. Binary compatibility is nothing but whenever we create a new class(also modifying a existing class) or a package it should be  compatible with the existing classes or packages.

Here they are insisting that the new packages (or a new class) should not create inconsistency when linking to the existing packages or a class. Have a look at the following program to understand this fact.

Here i have two classes A and B as follows.

Program:



import java.util.*;
import java.io.*;
public class A
{
public static void main(String args[])
{
B b=new B();
b.call();
}
}


class B

{
public static void call()
{
System.out.println("I am inside B");
}
}



Output:


I am inside B

As you see,these two programs works fine without any error. Now what am i going to do here is change the class B as an abstract class abstract class B and then compile the program B alone.



abstract class B
{
public static void call()
{
System.out.println("I am inside B");
}
}


Since there is no statements in class B that violates the semantics of java programming language,you will not get any error.

If you execute the class A without recompiling it then this java.lang.instantiationexception  is thrown  as follows.


import java.util.*;
import java.io.*;
public class A
{
public static void main(String args[])
{
B b=new B();
b.call();
}
}


Exception in thread "main" java.lang.InstantiationError: B
        at A.main(A.java:7)


What do you infer?


From this error you may infer one thing that the binary compatibility is not preserved by this modified class B. Since the class A is not recompiled it has no idea about the new state of class B,thus causing this exception to be thrown.

It is obvious that,if we would have recompiled the class A then you will get an error message at compile time rather than getting this exception thrown at runtime.

"But there are situations,at which this exception will be thrown even though you have successfully compiled the class."


Let's consider an example situation like as follows,

We people tend to have new packages or new application included in our own project.As we download the package(eg,a jar file),most of the people (may) tend to place this jar file on the jre/lib/ext to avoid classpath settings. 

if the new version of the package arrives and if you refer to this package by including it in the classpath then "during compilation the older version would be used for resolving the references but during execution the newer version will be referenced". Thus causing this exception to be thrown.

Have  a look at the following example,I have made two different versions of the  .class file of class B  and i packed it as two different jar files.I stored one file in jre/lib/ext and the other one is referred through classpath settings. Here class A will have reference to class B


C:\>cd blog

C:\blog>cd Tool

C:\blog\Tool>javac A.java

C:\blog\Tool>java A
I am inside B



C:\blog\Tool>set CLASSPATH=".;c:/blog/Tool/ganesh/t2.jar"

C:\blog\Tool>javac A.java

C:\blog\Tool>java A
Exception in thread "main" java.lang.InstantiationError: B
        at A.main(A.java:7)



As you see,before setting the class path it works fine but when the class path had been set this exception is thrown. So when using the new packages,remove the older version of the packages and try to set the classpath to point to this new version.

I have also discussed about this exception thrown for some other reasons in my older post.To view the older post Other Common reasons for Instantiation Exception.



Reason for java.lang.ClassFormatError

Class Format Error:

Here,i am going to present what i have learnt when dealing with byte codes in the class file.We all know that whenever a java program is successfully compiled,the class file would be generated.Then you may think how come this ClassFormatError is thrown at run-time.

So let's discuss about this error in detail  to know the reasons behind them.

In the java API documentation it is given that "this error would be thrown when the java virtual machine attempts to read a class file and founds that the class file has been altered in such a way that it loses its integrity."

Here they are trying to say that "if a class file has been modified in a complicated way  then this error would be thrown." 

There may be two possible ways a class file can get corrupted as far i know.

1.May be the compiler have some unresolved bugs in it.

2.The programmer may intentionally change the class file for some reasons.

You may ask,why am i gonna change a class file? after all it is compiled(and executed) successfully.The fact is that when you want to develop a state-of-the-art application then you must have to deal with byte codes.

So here you have to note an important thing that "this error will occur either if someone intentionally modified the class file or your compiler have some bugs in it."

I will show you know now how come this error occurs,Before that i want to remind you about the Hex editors.The Hex editors are applications which lets you edit the file that contains the hex codes. Since the class files contains Hex codes,we can able to edit it.

I have included a simple program that performs the addition of two numbers and i edited the class file using the hex editor to show you how this error occurs.

Program:

import java.io.*;
import java.util.*;
public class Add
{
public static void main(String args[])
{
int a;
int b;
a=1;
b=2;
int c=a+b;
System.out.println("The value is:"+c);
}
}

Have a look at the Hex codes contained in the class file generated for this program.






Consider the line 0C0: 01 00 0D 54 68 65 20 76 in which the second pair of Bytes contains 00(NOP) which means No operation. For the sake of optimizing the program i have changed the value 00 as 1D which loads a integer value from the local variable.







But doing so,causes java.lang.ClassFormatError to be thrown during run-time as follows:




The change that, i have made results in the truncation of the class file......

Thus while dealing with byte codes in the class file,ensure that you do not try to change the byte codes unnecessarily.Note that,even if you try to change the particular byte codes then you would not get this error,but your ultimate output would get changed.

So,while changing the byte codes be conscious about the consequences of your modification.




Handling Java.lang.NegativeArraySizeException

NegativeArraySizeException

The Negative Array size exception is one of the rarely occurring exception in java programming. Let's have a brief overlook on this exception.

If you  glimpse at the title,may be you would get an hint that this exception is related to size of the array.Yes,of course.It is related to the size of the array.

We have studied that,when defining an array in java(and almost in all the programming languages ) we should give a positive value for the size of the array.As we have read we used to give only positive values.

But,I guess we may not know what will happen if we give negative value to the size of the array?..

Even if you specify a negative value,the compiler will accept it and it will not show any error.The fact is that the compiler is designed to verify whether the value given for the size is an integer or not.

It will not check whether the given value is positive or not at the compile time and throws this Negative Array Size Exception.

We programmers,will not give negative value for an array size intentionally.But may be responsible for assigning a negative value.

There are certain situations in which the value for the size of an array goes negative.For example, You could have assigned the result of  a mathematical calculation to be the size value.If the mathematical calculation results in a negative value then you would be landed in a embarrassing situation.

So I suggest you to assert the result of an computation or a value read from a stream to be positive before assigning it as a size of the array.

Here i have included an example program that gives you an idea about when this exception is thrown.

Program:

import java.util.*;
import java.io.*;
public class Stacktest
{
public static void main(String args[])throws IOException
{
int c[]=new int[-2];
Scanner in=new Scanner(new InputStreamReader(System.in));
int b=in.nextInt();
int a[]=new int[b];
}
}


output:

-2
Exception in thread "main" java.lang.NegativeArraySizeException
        at Stacktest.main(Stacktest.java:10)


In the above program i have given the value for the size the array c[] as -2,Which is the reason for this exception to be thrown.

java.lang.ArrayStoreException

ARRAYSTOREEXCEPTION:


On reading the title itself,you would be able to identify that this exception is thrown when storing something(in appropriate) in an array.Lets discuss in detail about this ArrayStoreException  in this post.

In java API documentation it is given that,"If we try to store the objects of wrong type into an array of objects then this exception will be thrown".

The fact is that, if we try to store an object of one type into an array of objects of another type then this ArrayStoreException will be thrown.

Here is the simple example which explains this problem:

Object x[]=new String[3];
 x[0]=new Integer(10);// compiles without error but throws ArrayStoreException.

Here,In this first statement Object x[]=new String[3]; It constructs an array of objects(x[]) of String type i.e X[] refers to an array of objects of String type.

Now look at the second statement which tries to store the Integer object in to an array of string type. i.e, x[0]=new Integer(10);

You may wonder why this second statement compiles without an error? as it tries to store an integer object into an array object of String type.This explains us that,"arrays tends to enforce their element types at run-time".This is one of the main disadvantage of the arrays and it could be the reason why parameterized arrays are not supported by JVM,Since the erasure property of  generics enforce the type constraints at compile time

Have a look at this statements to know why i have said so,


List <Object> l=new ArrayList<String>();// incompatible error
l.add(new Integer(10));

When we use an ArrayList with a parameter type then at the compile time itself we would be able to identify whether the statement will execute without causing an error or not.

I have also included a program that causes this ArrayStoreException as follows.Let us review the program to identify the cause of this error.



PROGRAM:

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

class Vehicle
{
public Vehicle(String arg1,String arg2)
{
Vehiclename=arg1;
Vehiclecolor=arg2;
}
public String getname()
{
return Vehiclename;
}
public String getcolor()
{
return Vehiclecolor;
}
private String Vehiclename;
private String Vehiclecolor;
}


class Truck extends Vehicle
{
public Truck(String a1,String a2)
{
super(a1,a2);
}
public String getname()
{
return super.getname();
}
public String getcolor()
{
return super.getcolor();
}
}
class VDetails
{
public static void main(String args[])
{
Truck s1=new Truck("BENZ","WHITE");
Truck s2=new Truck("BMW","GREY");
Truck s[]={s1,s2};
Vehicle v[]=s;
v[0]=new Vehicle("THUNDERBIRD","SILVER");

}
}


OUTPUT:

Exception in thread "main" java.lang.ArrayStoreException: Vehicle
        at VDetails.main(VDetails.java:44)

This program has a parent class Vehicle and a child class Truck.As you see the program,i have tried to make an array object of class Vehicle type to refer to an array object of type Truck.


i.e, Vehicle v[]=s;


Thus this array v[] can only store objects of type Truck. If you try to store an object of other type then this exception would be thrown.

Thus in order to avoid this  exception i suggest you to use ArrayList wherever possible rather than using arrays as it will help you identify the error at compile time itself.




handling java.lang.illegalmonitorstateexception


IllegalMonitorStateException:


The most important thing in multi-threading is serializing the simultaneous access to the objects, otherwise these multiple threads will leave this object in an unstable state.For this purpose locks have been introduced.

The synchronized keyword is the easiest one for providing synchronization between the threads and it has an intrinsic lock associated with it.When a method is declared to be synchronized then only one thread can gain access to the method at a time.The next thread will get a chance only after the previous thread exits the method.

When a thread gains access but has no sufficient sources to accomplish its tasks then it has to give chance to other threads.For this purpose  wait(),notify(),notifyAll() methods  have been introduced.

Note: In Thread class there is no methods like wait() or notify() is available.It is only available in Object class.So any objects can call this method.Calling this method outside the synchronized block will also throw this exception.

In java API documentation it is given that calling these methods will throw java.lang. IllegalMonitorStateException when the current thread is not the owner of the object's lock.

Let us see in detail,when this illegalMonitorStateException is thrown.

There are two possible ways,a synchronized keyword can be used to acquire the lock.

1.A method can be declared as synchronized.

2.Using a synchronized block to acquire a lock on an specific object.

When a method is declared as synchronized,then all the threads are synchronized by the class object that contains this method i.e,All the threads can have locks over the class object.

I have explained this concept with a bank containing three accounts.we have to trasfer funds from one account to other accounts.This transfering process is carried out by each threads.

The following two programs are written by cay s.Horstmann in (Core Java,VolumeI),
Copyright© 2008 Sun Microsystems,Inc. I have modified this program so as to make it simple to explain this exception.

Program:


public class UnsynchBank
 {
 public static void main(String[] args)throws InterruptedException
 {
 Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
 int i;
 TransferRunnable r = new TransferRunnable(b, 0,1,500,INITIAL_BALANCE);
  t = new Thread(r);
  t.start();
TransferRunnable r2 = new TransferRunnable(b, 0,2,500,INITIAL_BALANCE);
  t1=new Thread(r2);
  t1.start();
}

 private static Thread t,t1;
 public static final int NACCOUNTS = 3;
 public static final double INITIAL_BALANCE = 1000;
 }

class Bank
 {
public Bank(int n, double initialBalance)throws InterruptedException
 {
 accounts = new double[n];
 for (int i = 0; i < accounts.length; i++)
 accounts[i] = initialBalance;
}

 public synchronized void transfer(int from, int to, double amount) throws InterruptedException
 {

while(accounts[from]
{
System.out.println("i am entering into wait set:"+Thread.currentThread());

wait();//This wait() method is called by the thread that has acquired lock on the class object Bank

}
 accounts[from] -= amount;
 accounts[to] += amount;
 System.out.println("I am the current thread:"+Thread.currentThread());
 System.out.println("source:"+from);
 System.out.println("to:"+to);
 System.out.println("amount:"+amount);
 System.out.printf("Total Balance: %10.2f%n", getTotalBalance());
 System.out.println("currentthread"+Thread.currentThread());

notify();//This notify() method is called by the thread that has acquired a lock on the class object Bank

 System.out.println();
 }

public synchronized double getTotalBalance()
 {
 double sum = 0;
for (double a : accounts)
 sum += a;
 return sum;
 }
 private final double[] accounts;
 }

class TransferRunnable implements Runnable
 {
public TransferRunnable(Bank b, int from,int to,int a, double max)
 {
 bank = b;
 fromAccount = from;
 toaccount=to;
 amt=a;
 maxAmount = max;
 }

 public void run()
 {
 try
 {

 int toAccount = toaccount;
 int amount = amt;
 bank.transfer(fromAccount, toAccount, amount);
 Thread.sleep((int) (DELAY * Math.random()));
 }
 catch (InterruptedException e)
 {
 }
 }

 private Bank bank;
 private int fromAccount;
 private double maxAmount;
 private int toaccount;
 private int amt;
 private int DELAY = 10;
 }


Output:


I am the current thread:Thread[Thread-1,5,main]
source:0
to:2
amount:500.0
Total Balance:    3000.00
currentthreadThread[Thread-1,5,main]


I am the current thread:Thread[Thread-0,5,main]
source:0
to:1
amount:500.0
Total Balance:    3000.00
currentthreadThread[Thread-0,5,main]

In the above program all the threads are synchronized by the Bank class object.I have shown this by highlighting those statements in the program. If you try to call wait() or notify() on any  other objects IllegalMonitorStateException will be thrown. For eg, if you try to call accounts.wait(); this will throw illegalmonitorstateexception because all threads have acquired the lock on the class object Bank not on the accounts object.


Using synchronized blocks:


Program:


In the above program change the transfer method as follows to use synchronized blocks to acquire locks.


 public  void transfer(int from, int to, double amount) throws InterruptedException
 {
synchronized(accounts) //All the threads are synchronized on the accounts object
{
while(accounts[from]
{
System.out.println("i am entering into wait set:"+Thread.currentThread());
accounts.wait();//wait() method is called by the thread that has a lock on the accounts object
}
 accounts[from] -= amount;
 accounts[to] += amount;
 System.out.println("I am the current thread:"+Thread.currentThread());
 System.out.println("source:"+from);
 System.out.println("to:"+to);
 System.out.println("amount:"+amount);
 System.out.printf("Total Balance: %10.2f%n", getTotalBalance());
 System.out.println("currentthread"+Thread.currentThread());

 accounts.notify();//notify() method is called by the thread that has a lock on the accounts object.
 System.out.println();
 }

 }


output:


I am the current thread:Thread[Thread-0,5,main]
source:0
to:1
amount:500.0
Total Balance:    3000.00
currentthreadThread[Thread-0,5,main]
Bank@1b67f74
Exception in thread "Thread-0" I am the current thread:Thread[Thread-1,5,main]ja
va.lang.IllegalMonitorStateException

        at java.lang.Object.notify(Native Method)
source:0        at Bank.transfer(UnsynchBank.java:70)

        at TransferRunnable.run(UnsynchBank.java:129)
to:2    at java.lang.Thread.run(Unknown Source)

amount:500.0
Total Balance:    3000.00
currentthreadThread[Thread-1,5,main]
Bank@1b67f74
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
        at java.lang.Object.notify(Native Method)
        at Bank.transfer(UnsynchBank.java:70)
        at TransferRunnable.run(UnsynchBank.java:129)
        at java.lang.Thread.run(Unknown Source)

If you see the program,all the threads are synchronized on the accounts object.So when calling the wait() or notify() method all the thread should specify the object on which it has acquired the lock,for eg, accounts.wait(). Simply calling the wait() method indicates that we are trying to call wait() on the bank object not on the accounts object.

So when we synchronize the threads using a paricular object obj.We should call obj.wait() or obj.notify().





java.lang.AssertionError


Assertion Error:

I guess we all know about assertions,which is one of the great tool to deal with the system failures.

Let us have an overview of how assertions differs from Exception handling technique.We all know about how assertions works.But anyway,Let's have a glance at assertions to know its advantage.

Assertions are used to evaluate a condition.If the condition gets failed then they will throw
java.lang.Assertion error.

Usage of Assertions:

1.assert a!=null;

This statement will check whether 'a' is null or not.If 'a' is null then this statement will throw an Assertion error. you could have thought of throwing an NullPointerException and  processing it using the try and catch block rather than using the Assertion error.

But one of the great advantage of assertions when compared to exception handling is that assertions allows us to use condition checks during testing and automatically removes the statements from the generated code thereby not affecting the execution speed.

If you have  lot of conditions to be checked in your program and have implemented exception handling techniques for violation of conditions,then this will slower the program execution.

I have shown this slowering of the program execution, using the two programs that i have included in this post.

When do we need this Assertion?


Note that the assertion should be used to deal with  unrecoverable errors or  errors that will disrupt operation of the entire program.Mostly it will not be used to deal with recoverable conditions.

one of the most common example where assertion can be used is explained through the sorting program.In the sorting program it would be used to check the validity of parameters passed.

If we want to sort an array of elements then before sorting it we should ensure that the array is not null.For this case assertion can be used.If an assertion error occurs then we can terminate the program rather than applying the sorting operations on that array.

The two different implementations of the sorting program that throws assertion error and also an other program which throws NullPointerException is given below.

program 1:
------------

 class Desc1
{
public void sort(int[] a)
{
int t;
for(int j=0;j<=5;j++)
{
for(int i=j+1;i<5;i++)
{
if(a[j]
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(int h=0;h<5;h++)
System.out.println(a[h]);
}
}
class Desc
{
public static void main(String args[])
{
long start=System.currentTimeMillis();
System.out.println("start time:"+start);
int a[]={2,7,4,5,6};
a=null;
try
{
assert a!=null:a;
Desc1 d=new Desc1();
d.sort(a);
}

catch(AssertionError e)
{
long end=System.currentTimeMillis();
System.out.println("End time:"+end);
System.out.println("Time elapsed:"+(end-start));
}
}
}


output 1:



C:\blog>javac Desc.java

C:\blog>java -ea Desc
start time:1341553937959
End time:1341553937959
Time elapsed:0




program 2:
----------



 class Desc1
{
public void sort(int a[])
{
int t;
for(int j=0;j<=5;j++)
{
for(int i=j+1;i<5;i++)
{
if(a[j]
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(int h=0;h<5;h++)
System.out.println(a[h]);
}
}
class Desc
{
public static void main(String args[])
{
long start=System.currentTimeMillis();
System.out.println("start time:"+start);
int a[]={2,7,4,5,6};
a=null;
try
{
if(a==null)
throw new NullPointerException();
Desc1 d=new Desc1();
d.sort(a);
}
catch(NullPointerException e)
{
long end=System.currentTimeMillis();
System.out.println("End time:"+end);
System.out.println("Time elapsed:"+(end-start));
}
}
}

output 2:


C:\blog>javac Desc.java

C:\blog>java -ea Desc
start time:1341554333676
End time:1341554333677
Time elapsed:1

C:\blog>



On comparing the output of the above two programs one thing seems to be obvious,which is the time taken to execute the program.

As you see the output of the program1,the time taken for program execution is 0 millisecond,wheareas the second program takes 1 millisecond for program execution.

Though this difference of 1 millisecond will not affect the performance of the program considerably,if you are dealing with some big projects where performance is of utmost importance the execution time does matters.

Suppose if you are in a postion to check many conditions and throw exceptions corresponding to the violation of each conditions then certainly the performance of the program will be affected because even after testing ,the code stays in the program which consumes some execution time.

Thus assertion offers better performance when compared to exception handling,as they remove the code after testing is over.


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