Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Performance Tip: Avoid Catching Exceptions

DZone's Guide to

Performance Tip: Avoid Catching Exceptions

Improve performance in your single thread app by catching the exceptions that can hinder performance and reduce response time.

· Performance Zone
Free Resource

In this post, we will look at simple example how catching exceptions impacts performance.

Code Sample

Code for Catching an Exception

private static void exceptionTest(){
 int i=0;
 int j=1;
 try{
 int k=j/i;
 }catch(ArithmeticException ex){
 //not good idea to catch run time exception but catch for demo only
 }
 }

Code Where Conditions are Handled

private static void withoutExceptionTest(){
 int i=0;
 int j=1;
 if(i>0){
 int k=j/i;
 }
 }

Method to Call Logic

private static long exceptionTestLoop(int iterations,boolean isCatchException){
 long startTime=System.nanoTime();
 for(int i=0;i<iterations;i++){
 if(isCatchException){
 exceptionTest();
 }else{
 withoutExceptionTest();
 }
 }
 long endTime=System.nanoTime();
 long time=endTime-startTime;
 return time;
 }

Main Method

public static void main(String[] args) {
 int itr=1000000;
 long timeForCatching=exceptionTestLoop(itr,true);
 long time=exceptionTestLoop(itr,false);
 System.out.println("Time for catching Exception "+timeForCatching+" without catching "+time);
 }

Results

exception_catch












Conclusion

Avoid catching exceptions as it will reduce response time. Above, the example demonstrates results for a simple single threaded application; however, the situation will become worst in multi-threaded environment.

Topics:
java ,performance tuning ,exceptions

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}