Friday, April 21, 2017

Exceptions-realtime

Error Types
---------------
NoClassDefinitionFoundError
StackOverFlowError
MemoryOutOfError
AssertionError

Un-Checked Exceptions
-----------------------------------
NullPointerException
NumberFomratException
ClassCastException
ArithmaticException
ArrayIndexOutOfBoundsException
NoSuchMethodException
ConcurrentModificationException
IllegalArgumentException
NoSuchElementException
UnSupportedOperationException

Checked Exceptions
------------------------
IOException
FileNotFoundException
ClassNotFoundException
SQLException
CloneNotSupportedException
ParseException
BadStringOperationException
CertificateException
DataFormatException
JAXBException
    MarshalException
    PropertyException
    UnMarshalException
    ValidationException
IOException
    EOFException
    FileNotFoundException
    RemoteException
    ZIPException
NoSuchFieldException
NoSuchMethodException
PrinterException
SOAPException
TimeOutException
TransformerException

NullPointerException
Yes, I am facing this Null Pointer exception most of my time when compare to other exceptions.
                This exception occurs .. if we are trying to perform any thing with the null object.
                The scenarios like when you are trying to access an object (Person Object ) from a list and which is not populated with the Person Objects and if it null object.

scenario-1(String)
--------------
             String str=null;   (str object does not have value)
             if(str.equals("java")){
                    System.out.println("yes! str equals to java");
             }else{
                   System.out.println("str  not equals to java");
             }

 In the above scenario, str is a String literal and which not initialized with string value. When trying to do equals operation with null then JVM throws Null Pointer Exception.

package com;
public class NullPointerExcep {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String str=null;
  if(str.equals("java")){
   System.out.println("yes! str equals to java");
  }else{
   System.out.print("str not equals to java");
  }
 }
}

outcome
---------
Exception in thread "main" java.lang.NullPointerException
 at com.NullPointerExcep.main(NullPointerExcep.java:11)

Scenario-2 (Object)
----------------

package com;
public class ObjectNull {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Object obj1 = new Object();
  System.out.println(obj1.hashCode());
  Object obj2 = null;
  System.out.println(obj2.hashCode());
 }
}

output
----------
4072869
Exception in thread "main" java.lang.NullPointerException
 at com.ObjectNull.main(ObjectNull.java:13)

On the third line inside main I'm explicitly setting the Object reference obj2 to null. This means I have a reference, but it isn't pointing to any object. 
After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a Null Pointer Exception because there is no code to execute in the location that the reference is pointing.

Scenario-3 ( with StringBuffer)
-------------------------------------

package com;

public class SBTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  StringBuffer buffer = null;
  if("Suneel".equals("Suneel")){
   buffer.append("Kumar");
  }
  System.out.println(buffer);
 }

}

outcome
--------
Exception in thread "main" java.lang.NullPointerException
 at com.SBTest.main(SBTest.java:12)

Fix
---
package com;
public class SBTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  StringBuffer buffer = null;
  if("Suneel".equals("Suneel")){
   buffer = new StringBuffer();
   buffer.append("Kumar");
  }
  System.out.println(buffer);
 }

}

output
--------
Kumar

best thing is either Instantiate the StringBuffer in the first itself or the place where you are using

StringBuffer buffer = new StringBuffer();

or 

StringBuffer buffer = null;
  if("Suneel".equals("Suneel")){
   buffer = new StringBuffer();
   buffer.append("Kumar");
}


NoClassDefinitionFoundError

Class definition means - defining the class in the first itself. So, NoClassDefinitionFoundError is thrown if class is referenced with "new" operator (i.e. static loading) but in the run time system can not find the referenced class.

Classes are statically loaded with Java’s “new” operator.
package com;
class MyClass {
             public static void main(String args[]) {
                    Flight flight = new Flight();
             }
}

Here Flight class should be in the class path Other wise it will throw NoClassDefinitionFoundError
MyClass - package com should be in the class path.

ClassNotFoundException 

A ClassNotFoundException thrown when an application tries to load in a class through its string using the following methods but no definition for the class with the specified name could be found
   forName("String class name ")  - in Class
   findSystemClass("String class name ") - in Class Loader
   loadClass("String class name"); - in Class Loader


code snippet
---------------
import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "mysqldb";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}
In the above code snippet , Class.forName(driver) will load the mysql driver class dynamically, while loading dynamically if that driver class not found then it will throw the ClassNotFoundException

To avoid this exception we need to set the build path with the mysql-connector-java-5.1.15-bin.jar file.


Oracle Connection Code

package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class MyDataBaseConection {


 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url = "jdbc:oracle:thin:@localhost:1521:XE";
    String dbName = "";
    String driver = "oracle.jdbc.driver.OracleDriver";
    String userName = "system"; 
    String password = "root";
    try {
    Class.forName(driver).newInstance();
    String sql = "select * from users";
    conn = DriverManager.getConnection(url+dbName,userName,password);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    while(rs.next()){
     System.out.println(rs.getString("FIRSTNAME"));
     
    }
    System.out.println("Connected to the database");
    conn.close();
    System.out.println("Disconnected from database");
    } catch (Exception e) {
    e.printStackTrace();
    }
 }


}

click here to download mysql-connector-java-5.1.15-bin.jar  file.
click here to download oracle jdbc jar file ojdbc14.jar , provided if you are using  oracle DB.

NumberFomratException

This exception occurs when we are converting  String to Number. 

lets us say 123 is the number , and if we convert this number to String that is fine . we did not get any exception in this case.
But "abc" is the string when we convert abc to Number.. definitely , because abc can not be converted to Number so, it will throw NumberFormatException.

Scenario
--------
package com;

public class NumberForatException {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String str ="123";
  int i = new Integer(str).intValue(); // it won't cause exception
  System.out.println(i);
  
  String str2 = "test";
  int j = new Integer(str2).intValue();  // cause exception
  System.out.println(j);
  
 }

}

Since "test" is a String and it can be converted to Number Obviously it will throw the NumberFormatException

123
Exception in thread "main" java.lang.NumberFormatException: For input string: "test"
 at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.<init>(Unknown Source)
 at com.NumberForatException.main(NumberForatException.java:15)

UnSupportedOperationException

This exception may occur in rare cases like when ever if we request operation on an Object which is not support.
like 
      Let's take an Array has number of Customer objects. for a case if i want to convert those Array in to List of customer objects 
then we do like this 
List<Customer> list = Arrays.asList(customerArray);
after above line of execution Customer Array will convert to List of Customer objects.
In result Arrays.asList will give 


static List asList(Object[] a)
          Returns a fixed-size list backed by the specified array.
it returns fixed size list.


Here is the complete java code 
-------------------------------------
package com;

import java.util.Arrays;
import java.util.List;
public class UnsupportedOperationExcp {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Customer customerArray[] = {new Customer("suneel","sunxxxx@gmail.com","India"),
         new Customer("sreenivas","sreexxxxxx@gmail.com","US"),
         new Customer("Kumar","kuxxxxx@gmail.com","India")};
  System.out.println("customerArray length :"+customerArray.length);
        List<Customer> list = Arrays.asList(customerArray);
        
         for(Customer customer : list){
          System.out.println("Customer Name :"+customer.getCustomerName());
          System.out.println("Customer Email :"+customer.getCustomerEmail());
          System.out.println("Customer Place"+customer.getCustomerPlace());
          System.out.println("----------");
         }
  }
 }

outcome
----------
customerArray length :3
Customer Name :suneel
Customer Email :sunxxxx@gmail.com
Customer PlaceIndia
----------
Customer Name :sreenivas
Customer Email :sreexxxxxx@gmail.com
Customer PlaceUS
----------
Customer Name :Kumar
Customer Email :kuxxxxx@gmail.com
Customer PlaceIndia
----------

Now lets see UnSupportedException - reproduce
since Arrays.asList will return fixed size and if we do add,remove or modify then that operation is not support on fixed size list.

package com;

import java.util.Arrays;
import java.util.List;
public class UnsupportedOperationExcp {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Customer customerArray[] = {new Customer("suneel","sunxxxx@gmail.com","India"),
         new Customer("sreenivas","sreexxxxxx@gmail.com","US"),
         new Customer("Kumar","kuxxxxx@gmail.com","India")};
  System.out.println("customerArray length :"+customerArray.length);
        List<Customer> list = Arrays.asList(customerArray);
      
         for(Customer customer : list){
          System.out.println("Customer Name :"+customer.getCustomerName());
          System.out.println("Customer Email :"+customer.getCustomerEmail());
          System.out.println("Customer Place"+customer.getCustomerPlace());
          System.out.println("----------");
         }
         
       list.remove(0);
      // list.add(new Customer("kk","gmail.com","UK"));  this one also throw exception
  }
 }

now code will throw unsupported exception 
outcome
----------
customerArray length :3
Customer Name :suneel
Customer Email :sunxxxx@gmail.com
Customer PlaceIndia
----------
Customer Name :sreenivas
Customer Email :sreexxxxxx@gmail.com
Customer PlaceUS
----------
Customer Name :Kumar
Customer Email :kuxxxxx@gmail.com
Customer PlaceIndia
----------
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.remove(Unknown Source)
 at com.UnsupportedOperationExcp.main(UnsupportedOperationExcp.java:27)


So, we should not do modify,add or remove on the list which is returned by Arrays.asList()

1 comment:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Agile coach during this lockdown period everyone can use it wisely.
    Certified agile coaching Bangalore

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...