Skip to main content

What Is Exception in java?

Exceptions are exceptional conditions in program flow.
What is the exceptional conditions?
  • You going to read a file. Exceptional condition: File is not found.(FileNotFound Exception)
  • You creating a new file. Exceptional condition: No space in memory for new file, you dont have rights to create a new file in drive.
  • You are performing some operation on object. Exceptional condition: object is null.(NullPointer Exception)
  • Mathematical exceptions like number divide by zero.(ArithmeticException)
  • Array related exception like accessing an index which not in array(ArrayOutOfBound Exception).
There are many cases where exception can occurs in your program. For your program runs as you expected,You need to perform exception handling for exceptional conditions but before go to exception handling lets know about Exception in java.

public class Test{
  
   void printName(){
     System.out.println("Test");
   }
   
   public static void main(String[] args) {
     Test test = null;
  //operation on null will gives nullPointerException
     test.printName();
   }
}





Exception
In java, Exception is a class and it comes in picture when any exception event occurs in your program.
Exception divided into two category: 1. Checked exceptions and 2. Unchecked exceptions
  1. Checked Exception OR Compile Time Exception:

    Checked Exceptions are those exception that occurs at time of compilation of your code, Its also known as compile time exception. These exception must be handled in code otherwise code not get compiled.
    Example: FileNotFoundException
    
    import java.io.FileReader;
    
    public class Test{
     
       public static void main(String[] args) {
            //Creating FileReader object for reading a file 
            FileReader file = new FileReader("C:\\code\\test.txt");
       }
    }
    
    Compile this application

    How to FIX it?
    By using exception handling. Please check my post for exception handling.
    
    import java.io.FileReader;
    
    public class Test{
       public static void main(String[] args) {
       
      try {
       //Creating FileReader object for reading a file 
        FileReader file = new FileReader("C:\\code\\test.txt");
      } catch (Exception e) {
                      //exception will catch i n this block if exception occurs. 
                      System.out.println("Some exception occurs in reading file");
    
                      //this code will give you full information on console about Exception
                      e.printStackTrace();
      }
            
       }
    }
    

    Java Program To Read File

    Above code get compiled without any exception, but for reading file we need some extra code.
    
    import java.io.FileReader;
    import java.io.BufferedReader;
    
    public class Test{
       public static void main(String[] args) {
       
      try {
       //Creating FileReader object for reading a file 
        FileReader file = new FileReader("C:\\code\\test.txt");
        BufferedReader fileInput = new BufferedReader(file);
        String str = "";
               while((str=fileInput.readLine()) != null){
               System.out.println(str);
                }
                fileInput.close();
      } catch (Exception e) {
                       //exception will catch i n this block if exception occurs. 
                       System.out.println("Some exception occurs in reading file");
    
                      //this code will give you full information on console about Exception 
               e.printStackTrace();
      }
     
       }
    }
    
  2. Unchecked Exception Or Runtime Exception:

    Exception occurs at time of execution known as Unchecked Exception or Runtime Exception. Unchecked exception use to come in program due to logical issue or improper java syntax.
    
    public class Test{
     
     public static void main(String[] args) {
     
        //Array of int, length= 4 
      //you can access value from 0 to 3 index
        int[] a = {2,1,3,5};
        
        //runtime exception if try to access value not with in index of array  
        System.out.println(a[4]);
     }
    }
    

    How to FIX it?
    You have to correct the program. In above program, you should not use out of array index.
  3. Error:

    Error are not exceptions, it can not be handled by program. Like Stack Overflow Error, Out of memory error.

Comments

Popular posts from this blog

Java Array, Multi Dimensional Array, Anonymous Array and Arrays Util Class

Array An array is a index based container object. The length of an array fixed at time of array creation. An Array holds a fixed number of values of a single type . One Dimensional Array Array can be created by two ways. Syntex: //1st way arraytype[] name = new arraytype[length]; //2nd way arraytype name[] = new arraytype[length]; 1st way is more readable. Examples: //charecyter Array Example: //creating Array of char, length 5 char[] charArray = new char[5]; //Initialize array elements charArray[0] = 'H'; charArray[1] = 'E'; charArray[2] = 'L'; charArray[3] = 'L'; charArray[4] = 'O'; //creating Array of int, length 4 int[] intArray = new int[4]; //Initialize array elements intArray[0] = 2; intArray[1] = 0; intArray[2] = 1; intArray[3] = 5; //creating Array of string, length 7 String[] weeks = new String[7]; //Initialize array elements weeks[0] = "mon"; weeks[1] = "tue"; weeks[2] = "wed"; w

String - A story of very special class in java

String is most used java class in any java project. Java treated String as special class. Lets see, what so special in String. String Basics String is group of characters. char[] chrs = {'i',' ','a','m',' ','h','e','r','o','.'}; String str = new String(chrs); System.out.println(str); /* Output: i am hero. */ String is an immutable class. Immutable class:  A java class which object can not be modified if once created. Because String class is immutable, String is final in nature, its mean you can not modify string object once you created. Default value of string is null. Simplest way to initialize String is //object created in String Literal Pool String str = "hello world"; Above example known as String literal, All string literals in Java programs, such as "hello world", are object of String class. Another way to create String object is //object created in Heap m