Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Monday, 15 May 2017

ClassNotFoundException vs. NoClassDefFoundError in Java

1) ClassNotFoundException:When we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass()or ClassLoader.findSystemClass()method and requested class is not available.

ClassNotFoundException occurs when class loader could not find the required class in class path. So, basically we should check our class path and add the class in the classpath.

NoClassDefFoundError: When a class is present during compile time but at run time the classes are changed or removed or class's static initializes threw exceptions.

2) ClassNotFoundException is a checked Exception derived from java.lang.Exception class and we can handle it while NoClassDefFoundError is an Error derived from LinkageError.

Sunday, 14 May 2017

InvalidClassException Exception in Java


java.lang.Object
            java.lang.Throwable
                        java.lang.Exception
                                    java.io.IOException
                                                java.io.ObjectStreamException
                                                            java.io.InvalidClassException


public class InvalidClassException extends ObjectStreamException

Throws when the Serialization runtime detects a problem with a Class:
1) The serial version of the class does not match that of the class descriptor read from the stream.
2) The class contains unknown datatypes.
3) The class does not have an accessible no-arg constructor.
4) The class is not public.
5) The class implements only one of writeObject or readObject methods.



Tuesday, 9 May 2017

NoClassDefFoundError in Java

java.lang.Object à  java.lang.Throwable à java.lang.Error à java.lang.LinkageError à java.lang.NoClassDefFoundError

public classNoClassDefFoundError extends LinkageError

When a class is present during compile time but at run time the classes are changed or removed or class's static initializes threw exceptions.

Scenario that when I faced NoClassDefFoundError

Due to Exception in Static Initializer
If we get any runtime exception while executing static initializer (static block or static variable declaration executes while load the class) and JVM class loader will not able to load class due ExceptionInInitializerError throws by static initializer, which will leads to NoclassDefFoundError.

class DivideClass {
     /**Here ArithmeticException will lead to
      * ExceptionInInitializerError which will lead to
      * NoClassDefFoundError
      */
     static {
           int undefined = 1 / 0;
     }
     public String method() {
           return "from divide class";
     }
}

public class TestException {
     public static void main(String[] args) {
           DivideClass d = newDivideClass();
     }
}

How to deal with the NoClassDefFoundError?
1. Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.

2. The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.

3. Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.

4. Check that there should not any runtime exception while loading the Class. 


Related Post:
ExceptionInInitializerError in Java



Sunday, 4 December 2016

Why Class CloneNotSupportedException is a checked Exception?

java.lang.CloneNotSupportedException - A Checked Exception

If the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

Why is it a checked Exception?
It was developed in earlier phase of the Java, there was very little experience of when it would make sense for an exception to be checked.

Some exceptions which are checked but probably shouldn't be and occasions where the exception is unchecked but should be checked.
Integer.parseInt throwing NumberFormatException probably being the clearest example.



Wednesday, 3 August 2016

Eclipse: java.lang.UnsupportedClassVersionError: Bad version number in .class file

When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError.

It generally occurs if a higher jdk version is used to compile the source file and lower jdk version is used to run the program.

Example:If you compile your java source file in jdk1.6 and try to run it on jdk 1.5, JVM will throw "java.lang.UnsupportedClassVersionError: Bad version number in .class file".


How to fix UnSupportedClassVersionError?

· Try to compile source code of that jar with the same JDK version which we are using to run the program (if source is available).


· If you don't have source try to find the compatible version of that library.

· Increase the jre version that is used to run the program.

I faced this problem while running an application on Web application on Eclipse and Tomcat. This is because there was version difference of Eclipse and Tomcat (lower jdk version in Tomcat).

I changed jre version of Tomcat to fix this problem.


Sunday, 22 May 2016

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver Exception comes when we try to connect Oracle database from java program and Oracle driver is not available in classpath.

Class.forName("oracle.jdbc.driver.OracleDriver") method loads a class at runtime using Reflection which throws ClassNotFoundException if the class "oracle.jdbc.driver.OracleDriver"is not found.

To resolve this issue, we need to include the ojdbc.jar JAR in application classpath. For Oracle 10g and 11g, these are present in ojdbc6.jar or ojdbc6_g.jar.

Wednesday, 16 March 2016

ExceptionInInitializerError in Java

java.lang.Object à  java.lang.Throwable à java.lang.Error à java.lang.LinkageError à java.lang.ExceptionInInitializerError

public class ExceptionInInitializerError extends LinkageError

Signals that an unexpected exception has occurred in a static initializer.

An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

Scenarios of ExceptionInInitializerError

Due to Exception in Static Initializer
If we get any runtime exception while executing static initializer (static block or static variable declaration executes while load the class) and JVM class loader will not able to initialize the class and throws ExceptionInInitializerError.

class DivideClass {

     /**Here ArithmeticException will lead
      * to ExceptionInInitializerError
      */
     static {
           int undefined = 1 / 0;
     }

     public String method() {
           return "from divide class";
     }
}

public class TestException {
     public static void main(String[] args) {
           DivideClass d = new DivideClass();
     }
}

Wednesday, 17 February 2016

Difference between ArrayIndexOutfOBounds and ArrayStoreException

ArrayIndexOutOfBoundsException: Since JDK1.0

ArrayIndexOutOfBoundsException occurs when your code tries to access an invalid index for a given array e.g. negative index or higher index than length - 1.

java.lang.Object à
   java.lang.Throwable à
      java.lang.Exception  à
         java.lang.RuntimeException  à
            java.lang.IndexOutOfBoundsException à
               java.lang.ArrayIndexOutOfBoundsException

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

ArrayStoreException:  Since JDK1.0

ArrayStoreException occurs when you have stored an element of type other than type of array.

java.lang.Object à
   java.lang.Throwable à
      java.lang.Exception  à
         java.lang.RuntimeException  à
            java.lang.ArrayStoreException

public class ArrayStoreException extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

Example:
Object x[] = new String[3];
x[0] = new Integer(0);


Sunday, 15 November 2015

What is difference between Checked and Unchecked Exception in Java?

Difference between Checked and Unchecked Exception

Checked Exception
Unchecked Exception
Checked Exception is required to be handled by compile time using try-catch block or else method should use throws keyword.

Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.
Super class of all checked exceptions is Exception.
Super class of all unchecked exceptions RuntimeException.

CheckedException represent scenario with higher failure rate.

Example: FileNotFoundException in reading a file that is not present.
Unchecked exceptions are mostly caused by poor programming.

Example: NullPointerException when invoking a method on an object reference without making sure that it’s not null.

Wednesday, 4 November 2015

Downcasting with java instanceof operator

When Subclass type refers to the object of Parent class, it is known as downcasting.

If we perform it directly, compiler gives Compilation error.

If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, down casting is possible.

class Parent1 {

}
class Child1 extends Parent1 {
      static void method(Parent1 obj) { 
           if(obj instanceof Child1){ 
                  Child1 obj1 = (Child1)obj//downcasting 
                  System.out.println("downcasting successfully !!"); 
           } 
      }
}

class DownCasting {
      public static void main(String[] args) {
            Parent1 obj=new Child1();
           Child1.method(obj);
     }
}

Output:
downcasting successfully !! 


If we apply the instanceof operator with any variable that has null value, it returns false.

Prefer polymorphism over instanceof and downcasting.

Tuesday, 3 November 2015

Why ConcurrentHashMap does not allow null keys and null values?

ConcurrentHashMap does not allow null keys and null values

According to Doug lea (author of the ConcurrentHashMap)

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) because there will be ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated.

The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped.

In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

The code is like this :

    
if(map.containsKey(k)) {
     return map.get(k);
} else{
     throw newKeyNotPresentException();
}

It might be possible that key k might be deleted in between the get(k) and containsKey(k) calls.

As a result, the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).

The Null key and value allowed in HashMap because there is no Concurrent access.

Friday, 9 October 2015

java.io.NotSerializableException

java.io.NotSerializableException is thrown when the object is not eligible for the serialization. We must implement the Serializable interface to make the class eligible for the serialization. This is a marker interface which tells the JVM that the class can be serialized.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

class Student {
      private String id;

      public String getId() {
            return id;
      }

      public void setId(String id) {
            this.id = id;
      }
}

public class NotSerializableExceptionTest {
      public static void main(String[] args) throws IOException{
            //Create FileOutputStream to create file
            FileOutputStream out = new FileOutputStream("student.dat");

            //Create ObjectOutputStream
            ObjectOutputStream outputStream = new ObjectOutputStream(out);

            //Create objects
            Student obj = new Student();
            obj.setId("001");

            //Write objects to stream
            outputStream.writeObject(obj);

            //Always close the stream
            outputStream.close();
      }
}

Output:
      Exception in thread "main"java.io.NotSerializableException: Student
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at NotSerializableExceptionTest.main(NotSerializableExceptionTest.java:30)

How to fix java.io.NotSerializableException?

Student class must implement the serializable interface.
Related Posts Plugin for WordPress, Blogger...