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

Difference between ClassNotFoundException and NoClassDefFoundError

When we see in general both ClassNotFoundException and NoClassDefFoundError are errors which comes when JVM or Class Loader not able to find appropriate class while loading at run-time. ClassNotFoundException is a checked exception and NoClassDefFoundError is an Error which comes under unchecked. 
There are different types of Class Loader loads classes from difference sources, sometimes it may cause library JAR files missing or incorrect class-path which causes loader not able to load the class at run-time. Even though both names sounds similar to class file missing there are difference between ClassNotFoundException and NoClassDefFoundError.
Difference between ClassNotFoundException and NoClassDefFoundError

ClassNotFoundException:
ClassNotFoundException comes when we try to load class at run-time using Reflection and if those class files are missing then application or program thrown with ClassNotFoundException Exception. There is nothing to check at compile time since its load those class at run-time. Best example is when we try to load JDBC driver class using reflection and we fail to point driver jars. Then program thrown with ClassNotFoundException as like below example.



import java.sql.Connection;
import java.sql.DriverManager;

public class ExceptionTest {

 public static void main(String[] args) {
  Connection conn = createConnection();
 }

 public static Connection createConnection() {

  Connection conn = null;

  try {
   Class.forName("com.mysql.jdbc.Driver");
   System.out.println("MySQL JDBC Driver Registered!");
   conn = DriverManager.getConnection(
     "jdbc:mysql://192.168.1.2:3306/mydatabase", "root", "root");

  } catch (Exception e) {
   System.err.println("Please configure mysql driver file !!!");
   e.printStackTrace();
  }
  return conn;
 }
}


OUTPUT:


Please configure mysql driver file !!!
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
 at java.net.URLClassLoader$1.run(Unknown Source)


These are the different class loaders from difference classes like,
forName method in class Class.
loadClass method in class ClassLoader.
findSystemClass method in class ClassLoader.


NoClassDefFoundError:

NoClassDefFoundError is thrown when a class has been compiled with a specific class from the class path but if same class not available during run-time. Missing JAR files are the most basic reason to get NoClassDefFoundError. As per Java API docs "The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found."


Lets see simple example to get NoClassDefFoundError Error.


public class SecondTestClass {

 public SecondTestClass(){
  System.out.println("Hello Java");
 }
}



public class ErrorTest {

 public static void main(String[] args) {
  new SecondTestClass();
 } 
}


NOTE:
Once you create both java files compile SecondTestClass.java and ErrorTest.java classes separately. Next delete the generated class file called SecondTestClass.class. Next try to run ErrorTest.class file which will thrown with NoClassDefFoundError error message.

OUTPUT:


Exception in thread "main" java.lang.NoClassDefFoundError: SecondTestClass
 at com.db.ErrorTest.main(ErrorTest.java:7)
Caused by: java.lang.ClassNotFoundException: SecondTestClass







Checked and Unchecked Exceptions in Java


Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. By using try-catch in a method and if any error occurs then object creates and handed over to the run-time system. Those objects are called as Exception object which contains information's about the exception occurred. 
In our earlier tutorial we have seen difference between throw and throws in java and these exception objects are called as throwing an exception to the run-time system. Normally there are 3 types of Exceptions in Java and they are 

1. Checked exception (or) Compile time exception 
2. Unchecked exception (or) Run-time exception
3. Error 

Below are the Exception hierarchy in Java.


Checked and Unchecked Exceptions in Java


Checked Exception:

Exceptions which are checked under the block or method and caught at compile time are called as checked exceptions. For example if we are reading a file with input as file name and by mistake file name supplied with wrong name then FileNotFoundException will be thrown from the constructor for non-existing file. A well written program will catch those exception and passed to the run-time system. 

Unchecked Exception:

Unchecked Exception are also called as run-time exception which are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These are usually called as programming bugs are API errors which occurs at run-time. For example consider a method passes the file-name to other method. By some programming flaws its started sending null to the method which caught under NullPointerExpcetion.

Errors: 

Errors also called as unchecked exceptions which are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. For example if application successfully opens a input file, but is unable to read the file because of a hardware or system failure are called as Errors which can't be recovered. 

Below are the few list of checked and Unchecked exceptions in java 

Checked Exceptions:

Exception
FileNotFoundException
ParseException
IOException
NoSuchFieldException
NoSuchMethodException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException


Unchecked Exceptions:

NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
AssertionError
NoClassDefFoundError
ClassCastException
StackOverflowError
IllegalArgumentException
IllegalStateException
ExceptionInInitializerError


Try, Catch and Finally in Java

In this tutorial we will see about try, catch and finally blocks in Java. When we talk about these 3 blocks its come under Exception Handling and one on the finest feature in Java to handle both checked and UN-checked exceptions.

  • try() - Try block used to hold statements which may cause exception at compile time or at run-time. Those statements will be surrounded with try block.
  • catch() - Catch block used to catch if any exception occurred in try block statements. Basically list of exceptions will be specified in the catch statement as like given below examples. Before Java 7 each exception should be specified in separate catch blocks and need to catched. But in Java 7 we have got a cool feature to use multi-catch exception handling. Please refer to our earlier tutorial for Java 7 multi-catch
  • finally() - Finally block will execute no matter whether if any exception occurred or not occurred, always finally block will be executed except 
    • - if there are any infinite looping in try or catch block
    • - or if System.exit statement present in try or catch block.
There are few interview questions were interviewer will be asked,

1. Try block can be without catch block?
Answer: Yes, but finally block is necessary in that case. 

2. Try and catch block can be without finally block?
Answer: Yes

3. Finally block can be without try or catch?
Answer: No, finally must be placed with try or try & catch block. 

4. Single try block can have multiple catch blocks?
Answer: Yes

5. Can we have multiple finally blocks?
Answer: No, for single try and catch there must be only 1 finally block.


Lets see few examples

EXAMPLE - 1


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 20;
  
  }catch (NumberFormatException e) {
   System.out.println("NumberFormatException occured !!!");
   return 5;
  
  }catch (Exception e) {
   System.out.println("Exception occured !!!");
   return 30;
  
  }finally{
   return 10;
  }
 }
}

OUTPUT:


NUMBER : 10


EXAMPLE - 2


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  int number = myFunction();
  System.out.println("NUMBER : "+number);
 }
 
 public static int myFunction(){
  try{
   return 50;
  }finally{
   return 100;
  }
 }
}

OUTPUT:


NUMBER : 100


EXAMPLE - 3


public class TryCatchFinallyTest {

 public static void main(String[] args) {
  String name = null;
  myFunction(name);  
 }
 
 public static void myFunction(String name){
  try{
   System.out.println("LENGTH: "+name.length());
   System.out.println("NAME: "+name);
  
  }catch (NullPointerException e) {
   System.out.println("NullPointerException occured !!!");
  
  }finally{
   System.out.println("Finally Executed...");
  }
  System.out.println("Function finished ...");
 }
}

OUTPUT:


NullPointerException occured !!!
Finally Executed...
Function finished ...







How to Create User Defined Exception in Java?

In this tutorial we will discuss about how to create User Defined Exception in Java. Since already Java contains all pre-defined Exceptions and why we need to create User Defined Exceptions in our Application?
To Handle our application specific Exceptions can be placed under User Defined Exception. 

To create our own Exception class we need to extend Exception class in our class. By this all base class (Throwable) methods will be extended to our Exception class.

Methods from Throwable class are


String toString()
String getMessage()
void printStackTrace()   
String getLocalizedMessage()
Throwable fillInStackTrace()   
void printStackTrace(PrintStream stream)   


For example in our online portal application users age should not be less than 18 and should not be greater than 35. So as per their age we need to allow users to access the application. So here we can create our own Exception to handle the users age from 18 to 35. If users age not matches the condition then we need throw a Exception.
 

Lets see small example Java code as how to write User Defined Exception in Java.

public class MyException extends Exception{

 public MyException(){
  super();
 }
 public MyException(String expSrt){
  super(expSrt);
 }
 public String toString(){
  return "Exception: Age should be 18 to 35 years only";
 }
}



public class MyApplication {
 public static void main(String[] args) {
  int age = 15;
  try{
   if(age < 18 || age > 35){
    throw new MyException(); // Line 8
   }else{
    System.out.println("Valid to access the application");
   }
  }catch (Exception e) {
   e.printStackTrace();
  } 
  
 }
}


OUTPUT:


Exception: Age should be 18 to 35 years only
 at com.test.MyApplication.main(MyApplication.java:8)


By above way we can define our own Exceptions for our application needs.