Common Java Exceptions and Solutions

Here we will see about java exceptions. An exception (or exceptional event) is a problem that arises during the execution of a program.I am sure that you might have faced below exceptions in your java applications.

NullPointerException

We can avoid nullpointer exception using apache utility classes easily. Using Apache Commons Lang relevant jar in your project classpath and import the correct class.

ClassNotFoundException

As the name suggests ClassNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn’t found the requested class in classpath. You need to add required jar in your classpath.

Also you may this in the spring based application like below.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

In Eclipse – > Right Click on Project and Click Deployment Assembly – > Select Java Build Path Entries -> Add Maven dependencies

NoClassDefFoundError

This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

IllegalArgumentException

Thrown when a method receives an argument formatted differently than the method expects.The only thing you must do is correct the values of the input parameters.

ArrayIndexOutOfBoundsException

Thrown when attempting to access an array with an invalid index value.You should check that your index is not negative and not higher than the array length before accessing an array item.

ClassCastException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

Solution: Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.

You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.

IllegalStateException

It is used to indicate that “a method has been invoked at an illegal or inappropriate time.

I hope above solutions will be really helpful to handle the java exceptions. If you missed any common java exceptions please use the below comment section to add it in the above list.

About mohan

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

© Copyright 2010-2016 www.techpages.org · All Rights Reserved · Powered by WordPress ·