Pages

Monday, May 25, 2020

Exception Handling in Java


What is exception?

Any abnormal condition of a program is called as exception. Handling of such mechanism is called as Exception handling.

Hierarchy of exception is as below:

Hierarchy of exception
Fig: Exception Hierarchy

Use of Exception handling:

It is used to maintain a normal flow of program.
Eg:
1 - - - -
2 - - - -
3 - - - -
4 - - - -
.
.
Let’s consider there are number of line of program as above. If exception occurs at line number 3rd then code below 3rd line will not execute and leads to abnormal execution or  termination of the program.
So for that we have to handle that Exception in proper manner. How to handle an exceptions we will see in below sections.



public class ExceptionBasic{
     public static void main(String args[]) {
        int data = 100 / 0; //line of code that may raise exception
        System.out.println(e);
         }

      }

In above program, exception may raise at line number 3 (i.e. 100/0). So we need to handle it to avoid termination of program abnormally.


Keywords used in exception handling:

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

1. try block:
Used to write any risky code where we feel that some part/line of program may raise an exception.

2. catch block:
This block used to catch any exception which is raised in try block and leads to normal termination.

3. finally block:
This block is neither used to write risky code nor to catch exception.
Finally block is always get executed, so it should be used to clean/close the resources  /session/database connections etc which were already opened.

4. throw:
Used to throw an exception. It is followed by class instance.
Declare inside method.

5. throws:
Used to declare an exception. It is followed by Class name only.
Declared with method signature.


Let’s see first try-catch-finally blocks: 

try-catch-finally combinations in program:


Rules for combinations are as below:
  • Every try should be followed by 
  • Single catch or 
  • Multiple catch or 
  • Single finally or 
  • Single catch and single finally or 
  • Multiple catch and single finally.

1.  try {
                       
            }
            catch(X e)  // correct
            {          
            }
2. try {
                       
            }
            finally  //correct
            {          
            }
3. try {
                                                                
            }
            // CE: try without catch/finally    
CE: Compile time error                            
      4. catch(x e)                                                      {                                                     
            }
            //CE: catch without try

       5. finally( ) 
            {
            }
            //CE: finally without try
       6. try {      
            }
  catch(X e)
            {           
            }
catch(X e) //Same Exception X catch again
            {
            }
// CE: Exception x has already caught
       7. try {    
            }
            catch(X e)
            {          
            }
    catch(Y e)
            {
            }
//It will compile, if no relation between class X and Y class
   
        8. try {    
             }
           catch(Exception e) 
            {          
            }
    catch(ArithmeticException e)
            {
            }
// CE: Exception java.lang.ArithmeticException has already been caught

 (Note: AArithmeticException is subclass of Exception, so its been catched before in Exception class)
      6.    try {           
             }
            catch(ArithmeticException e)
            {           
            }
            catch(Exception e)
            {           
            }
       
(Note: Runs for Arithmetic exception 1st catch block will handle and for non-ArithmeticException 2nd catch block will handle)
      7.    try {
               //CE: try without catch/finally

            System.out.println("Hello");
           
       catch(Exception e)
            {
              } //CE: catch without try

(Note: There should NOT be any statements between any blocks: try-catch-finally)
      8.    try {                        
             }
            catch(X e)
            {         
            }
            System.out.println("hello");
            catch(Y e)
            {
            } //CE: catch without try

            
Note: we can write Sop("") inside try-catch-finally but if we write outside block like in above example then it gives CE
       9.    try {       
               }
            catch(X e)
            {          
             }
            System.out.println("hello");
            finally
            {          
            }

//CE: finally without try
      10. try {         
             }   
            catch(X e)
            {          
            }       //correct
            try {
                       
            }
            finally
            {
             }      //correct
       11.  try {
               }
            finally {            
            }
            catch(X e) {

            }
// CE: catch without try
12. try {
            }
           
            catch(X e) {
                       
            }
            finally
            {
                       
            }
            finally
            {
                       
            }
            //CE: finally without try
       13.  try {
                 try {                
                        }
                 catch(X e) {        
                    } //try-catch inside try block
         finally
                {
                                   
                  }
            }

//correct
       14. try {
                  try {                   
                        }
                 catch(X e) {                   
                        }
            }
//CE: try without catch or finally
       15.  try {          
               }
        catch(X e) 
              {
                   try {                  
                          }
                   finally {               
                             }       
               }
//correct (Try-finally blocks inside catch)
      16. try {            
             }
      catch(X e) {       
                        }
            finally {
                         try {                        
                                }
                  finally {                 
                               }         
                        }
//correct
                                   
      17.   try {
               try {                                 
                      }
               catch(X e) {         
                                 }
               }
//CE: try without catch or finally
      18. try
           
            System.out.println("try");      
            catch(X e) {                       
                              }

//CE: curly braces are mandatory for try-catch-finally
      19.  try {           
              }                      
            catch(X e);
            System.out.println("catch");

//CE: curly braces are mandatory for try-catch-finally
20. try {                       
            }                       
            catch(X e) {           
                              }
            finally
            System.out.println("finally");

//curly braces are mandatory for try-catch-finally 
21.   try
      System.out.println("try");               
   catch(X e) {                                      
                        }

//curly braces are mandatory for try-catch-finally
      22. try {     
            }                  
            catch(X e) {          
            }
            finally
            System.out.println("finally");

//curly braces are mandatory for try-catch-finally 
      23.    try {       
            }                  
            catch(X e)
            System.out.println("catch");

//curly braces are mandatory for try-catch-finally


Basic Program of try-catch-finally: 

public class ExceptionBasic{
     public static void main(String args[]) {
          try {
              // code that may raise exception
              int data = 100/0;
          } 
          catch (ArithmeticException e) {
                System.out.println(e);
          }
          finally {
               System.out.println("Finally block executed");
          }      
          // rest code of the program
          System.out.println("Rest of the code...");
     }
}

Output:
java.lang.ArithmeticException: / by zero
Finally block executed
Rest of the code...

From above example we can say that line: int data = 100/0 may raise an exception so we have declared an exception in catch block. 
If exception occurred in try block matched with exception declared in catch block (Same exception of Super class of that Exception) then only exception will get handled and program will terminate normally i.e. all program will executed.

Note: 
1. try-catch-finally blocks can be written inside methods/static or non-static blocks.
2. We should be careful while writing code inside try-catch-finally blocks to normal termination.



Control flow in try-catch-finally:


public class A {        

            try {
                        Statement 1;
                        Statement 2;
                        Statement 3;
            }
            
            catch(Exception e) {
                        Statement 4;
            }
           
            finally {
                        Statement 5;
            }
            
                      Statement 6;          

            }
}



Case 1: If no exception occurs
Output: All Statements 1, 2, 3, 5, 6 will be executed except catch block. 
(Note: if the exception occurred in try block and then catch block will execute only if exception matched in catch block.)

Case 2:  If exception occurs at statement 2 and handled in catch block.
Output: Statement 1,4,5,6 executed (normal termination).

Case 3: If exception occurred at statement 2 and not handled by catch block.
Output: Statement 1, 5 executed (Abnormal termination).

Case 4: If exception occurred at statement 4.
Output: Statement 1, 2, 3, 5 and 6 executed (Abnormal termination).

Case 5: if exception occurred at statement 5.
Output: Statement 1, 2, 3 executed (finally block wont execute).

Case 6: if exception occurred at statement 6.
Output: Statement 1, 2, 3, 5 executed (Abnormal termination).

Case 7: if exception occurs above try block then nothing will be displayed as output.



Note:
        1. There should not be long code inside try { } block, because if exception occurs at particular line then code below that line will not execute.

       2. Catch block only executed when exception occurs in try and handled in catch.
i.e. if exception occurs in try block & matched/ handled in catch block then catch block is execute otherwise not execute the catch block.

      3. Finally block always executed but it will not get executed if exception occurs in finally block or calling System.exit(0) or execution occurs at the beginning before try block.

      4. If we calls System.exit(0) (exit() method of System class) then it will not shows any exception on console whether it occurs or not.


What is difference between throw vs throws:




throw
throws
1
Followed by instance
Followed by class name
2
Used to throw exception
Used to declare exception
3
Can’t throw multiple exception
Can declare multiple exception
4
Use inside method
With method declaration
5
Unchecked exception can’t propagate using throw
Unchecked exception can propagate using throws
6
Used to throw custom exception (user define exception)
Can but usually Not used to throw custom exception
7
Used to handle exception
If we don’t want to handle exception then use throws
8
Used in try block or method throws exception
Not used in try-catch used with method signature
9
Not improves readability
It improves readability
10
e.g. used to break switch statement without break keyword.
Can’t use to break switch statement


Example of throw keyword:

In below example, we have created validate( ) method which takes integer as input.
If the age <18, then we are throwing the ArithmeticException otherwise print a message "welcome to vote".


public class Marriage {
     static void validate(int age) {
          if (age < 18)
              throw new ArithmeticException("Not eligible");
          else
              System.out.println("welcome to vote");
     }
   public static void main(String args[]) {
          validate(13);
          System.out.println("rest of the code...");
     }
}

Output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible
at blog.Marriage.validate(Any.java:5)
          at blog.Marriage.main(Any.java:11)



Example of throws keyword:

If we don’t want to handle exception then use throws. Unchecked exception can propagate using throws. Multiple exceptions can be declared using throws.

In below example, exception thrown if age <18 (print "Access denied"). If age is 18 or older then print"Access granted":

public class VotingMachine {
  static void checkAge(int age) throws ArithmeticException {
    if (age < 18) {
      throw new ArithmeticException("Access denied");
    }
    else {
      System.out.println("Access granted!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}

Note:
We can use throws and throw in single program.

When to use: If we know that, some part of our code may raise an exception and we do Not want to handle that exception then we should go for throws keyword.


Exception Hierarchy classes as below:



Errors:

  • It’s a class which extends Throwable class.
  • Compiler find something wrong with your program is called as Error.
  • Errors can NOT be handle while exceptions can able to handle.

Checked Exceptions:

  • Exception checked at compile time is called ac Checked Exceptions.
  • E.g. SQLException, InstantiationException, FileNotFoundException etc.

Un-Checked Exceptions:

  • Exception checked at Run time is called ac Un-Checked Exceptions:
  • E.g. NullPointerException, ArithmaticException etc.



Let’s see difference between checked and unchecked exception which is common interview question.

Difference between checked and unchecked exception:



Checked exception
Unchecked exception
1
Checked at compile time.
Checked at runtime.
2
Except RuntimeException and error under execution hierarchy.
Comes under RuntimeExecution class.
3
Can’t propagate: give compile time error.
Can propagate.

4
Exception handling used to handle checked exception.
Caused due to programmer's mistake.
5
Checked by compiler.
Checked by JVM.
6
Compiler always check in case of checked exception
Compiler won’t check whether programmer handling exception or not.
7
E.g. SQLException,   FileNotFoundException, etc.
E.g. NullPointerException, ArithmaticException, etc.



Most popular Errors and Exceptions are as below: (There are many but I have explained few exceptions here)

Error:


1. StackOverflowError:
Comes when stack is overflow due to recursion i.e. calling this method from another and another method from this. 

2. OutofMemoryError:
When heap size becomes full then it becomes full when lot of objects are created in heap.

3. NoClassDefFoundError:
If class is not found at runtime. If A.java class we compile by B.java (javac B.java). 



Checked Exception:


1. SQLException :
 If we don’t write schema name, table name of database then gives this exception.

2. InstantiationException:
If we pass parameterized constructor in servlet class because, class will loaded by using newInstance() and for that only default constructor is required.

3. FileNotFoundException :
It uses property file in project gives this exception because, file name was not matches at runtime.

4. NoSuchMethodException : (if main signature is not correct)
Gives exception if we didn’t found method of action class in structs at runtime.

5. ClassNotFoundException 
Dynamically allocated class not found at runtime e.g. action class/ Driver class.

6. BindException :
If the port is already in use then gives this exception. (This will face only when you are using Tomcat)



Unchecked Exceptions:


1. ArithmeticException: 
Occurs when found result as divide by 1/0

2. NullPointerException:
Getting null value returns from database/anywhere.
Eg.
    String s = null;
    System.out.println(s.length()); //Occur NullPointerException 

3. ConcurrentModificationException:
If we try to modify earliest Hashmap while iterating then gives ConcurrentModificationException (Pleas check Map section).

4. IllegalArgumentException:
If we start the server without deploying the web project.

5. NumberFormatException:
Caused when wrong formatting of an value assigned to other.
Eg.
    String s = "abc";
    int i = Integer.parseInt(s); // NumberFormatException



6. ArrayIndexOutOfBoundsException:
This exception occurs If we are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
Eg. 
    int a[] = new int[5]; //Index value upto 5
    a[10] = 50; //ArrayIndexOutOfBoundsException



Methods used to print an Exception:

  • getMessage() : Display only exception description
  • toString() :  Display exception name, exception description. 
  • printStackTrace() : Display the exception name, exception description and at which line exception occurred. 
Note: JVM will use “Default Exception Handler” to print information about exception, it uses e.printStackTrace() internally by default. 


Program to print an exception:


class A {

     public static void main(String[] args) {

     try {
          int i=10/0;
          System.out.println(i);
         } 
    catch (ArithmeticException e) {
    System.out.println("1. Using getMessage(): "+e.getMessage());
    System.out.println("----------------------------------------");

    System.out.println("2. Using toString(): "+e.toString());
    System.out.println("----------------------------------------");

    System.out.println("3. Using printStackTrace():");
    e.printStackTrace();
          }
     }
}


Output:

1. Using getMessage(): / by zero
---------------------------------------------
2. Using toString(): java.lang.ArithmeticException: / by zero
---------------------------------------------
3. Using printStackTrace():
java.lang.ArithmeticException: / by zero
at blog.A.main(A.java:8)


Note: 
Interview question and some advance programs will be covered in another section. Thanks




1 comment:

**** Please let me know if you have any doubts. ****