World's most popular travel blog for travel bloggers.
Showing posts with label basic java. Show all posts
Showing posts with label basic java. Show all posts

A. Exception Propagation : Unchecked Exception

Before explaining the concept of exception propagation , review the below code with care –
class ExceptionPropagation{
  
  void method3(){
    int result = 100 / 0;  //Exception Gere
  }
  
  void method2(){
    method3();
  }
  
  void method1(){
    try{
 method2();
    } catch(Exception e){
 System.out.println("Exception is handled here");
    }
  }
  
  public static void main(String args[]){
 ExceptionPropagation obj=new ExceptionPropagation();
 obj.method1();
 System.out.println("Continue with Normal Flow...");
  }
}

Output :

Exception is handled here
Continue with Normal Flow...

Explanation : Exception Propagation

When exception is occurred at the top of the stack and no exception handler is provided then exception is propagated –

We can see that
  1. exception is occurred in the method3() and in method3() we don’t have any exception handler.
  2. Uncaught exception will be propagated downward in stack i.e it will check appropriate exception handler in the method2().
  3. Again in method2 we don’t have any exception handler then again exception is propagated downward to method1() where it finds exception handler
Thus we can see that uncaught exception is propagated in the stack until stack becomes empty, this propagation of uncaught exception is called as Exception Propagation.

B. Exception Propagation : Checked Exception

class ExceptionPropagation{
  
  void method3(){
    throw new java.io.IOException("Checked Exception..");
  }
  
  void method2(){
    method3();
  }
  
  void method1(){
    try{
 method2();
 } catch(Exception e){
 System.out.println("Exception is handled here");
 }
  }
  
  public static void main(String args[]){
 ExceptionPropagation obj=new ExceptionPropagation();
 obj.method1();
 System.out.println("Continue with Normal Flow...");
  }
}

Output :

Compile Time Error
You must remember one rule of thumb that – “Checked Exceptions are not propagated in the chain“. thus we will get compile error in the above case –

External More Help :

Refer this guide to know more about important guidelines on Exception propagation

Java throw exception

The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
  1. throw exception;  
Let's see the example of throw IOException.
  1. throw new IOException("sorry device error);  

java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
  1. public class TestThrow1{  
  2.    static void validate(int age){  
  3.      if(age<18)  
  4.       throw new ArithmeticException("not valid");  
  5.      else  
  6.       System.out.println("welcome to vote");  
  7.    }  
  8.    public static void main(String args[]){  
  9.       validate(13);  
  10.       System.out.println("rest of the code...");  
  11.   }  
  12. }  
Output:
Exception in thread main java.lang.ArithmeticException:not valid

Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

  1. ....  
  2. try  
  3. {  
  4.     statement 1;  
  5.     statement 2;  
  6.     try  
  7.     {  
  8.         statement 1;  
  9.         statement 2;  
  10.     }  
  11.     catch(Exception e)  
  12.     {  
  13.     }  
  14. }  
  15. catch(Exception e)  
  16. {  
  17. }  
  18. ....  

Java nested try example

Let's see a simple example of java nested try block.
  1. class Excep6{  
  2.  public static void main(String args[]){  
  3.   try{  
  4.     try{  
  5.      System.out.println("going to divide");  
  6.      int b =39/0;  
  7.     }catch(ArithmeticException e){System.out.println(e);}  
  8.    
  9.     try{  
  10.     int a[]=new int[5];  
  11.     a[5]=4;  
  12.     }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}  
  13.      
  14.     System.out.println("other statement);  
  15.   }catch(Exception e){System.out.println("handeled");}  
  16.   
  17.   System.out.println("normal flow..");  
  18.  }  
  19. }  
Before Java 7, we used to catch multiple exceptions one by one as shown below.
catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}
In Java 7, we can catch both these exceptions in a single catch block as:
catch(IOException | SQLException ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.

Syntax of java try-catch

  1. try{  
  2. //code that may throw exception  
  3. }catch(Exception_class_Name ref){}  

Syntax of try-finally block

  1. try{  
  2. //code that may throw exception  
  3. }finally{}  

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.
  1. public class Testtrycatch1{  
  2.   public static void main(String args[]){  
  3.       int data=50/0;//may throw exception  
  4.       System.out.println("rest of the code...");  
  5. }  
  6. }  
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.
  1. public class Testtrycatch2{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       int data=50/0;  
  5.    }catch(ArithmeticException e){System.out.println(e);}  
  6.    System.out.println("rest of the code...");  
  7. }  
  8. }  

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.

Internal working of java try-catch block



The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
  • Prints out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occurred).
  • Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

Multiple Catch Blocks

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −

Syntax

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example

Here is code segment showing how to use multiple try/catch statements.
try {
   file = new FileInputStream(fileName);
   x = (byte) file.read();
} catch (IOException i) {
   i.printStackTrace();
   return -1;
} catch (FileNotFoundException f) // Not valid! {
   f.printStackTrace();
   return -1;
}

The Finally Block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −

Syntax

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}finally {
   // The finally block always executes.
}

Example

 Live Demo
public class ExcepTest {

   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
This will produce the following result −

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −
  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses whenever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.