Home > DeveloperSection > Articles > Exception Handling in Java

Exception Handling in Java

Java Java 
0 Comment(s)
 621  View(s)
Rate this:

Exception Handling in Java

Basically errors have two types

1.      Compile Time Errors-:  Compile times errors means errors of syntax. For example we have a method which take String parameter but we give us Integer parameter then it will be show compile time errors e.g.

Public void setData(String text




// Call method


// Error because this method takes only String argument not an integer value.

2.      Runtime Errors-: Runtime error means syntax are correct but errors in logical problems. For example

       int a[] = new int[2];

System.out.println("Access element three :" + a[3]);

It will be throws exception ArrayIndexOutOfBoundException because in array object have only 2 index but we are getting value from third indexes so it will be throws exception.

Any logical error which we can handle called exception.

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

·         A user has entered invalid data.

·         A file that needs to be opened cannot be found.

·         A network connection has been lost in the middle of communications or the JVM has run out of memory.

For example

int value=Integer.valueOf("1k");

int data type store only number or integer value it can’t store any character or String. So it will be throws runtime exception.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.


For handle Exceptions use Try and catch. Add your code in try block and if any exception find then terminate your cursor from try block and then handle exception in the help of catch block. You can also add finally block which run every time if exception find or not.


  public static void main(String args[])




    type your code here.


    catch (Exception ex

     {  }



     Add your code for executed everytime



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.

Here a sample of exception handling

public class Sample {

     public static void main(String args[]) {

           int a[] = new int[2];

           try {


                System.out.println("Access element three :" + a[3]);

          } catch (Exception ex) {

           } finally {

                System.out.println("Finally block");






It will throws exception ArrayOutOfBoundException but it handle by catch block,finally block code will be exceuted


Output-: Finally block


Don't want to miss updates? Please click the below button!

Follow MindStick