Over a million developers have joined DZone.

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

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

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.

Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:
java ,performance tuning ,exceptions

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}