Exception Handling Tutorials in Java

0
170
Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

It is one of the important aspect of exception in java tutorial.As all the other exceptions are child class of Class Exception so we can catch multiple exceptions with a single catch statement. In that case no further searching happens.once we have given the statement like catch(Exception e) , all exceptions will be trapped here.Lets see exception handling in java with examples. This is one of the exception handling in java best practices.


public class myMultiCatchException{
    static String a[]={"Hello","Java"};
    static String myString=null; 
    public static void main(String []args){
    try{
    if(a[2].equals("hi"))
    System.out.println("hi");
    if (myString.equals("hello"))
    System.out.println("true");
}
catch(Exception e)
{
System.out.println("An Exception has come");
}
}
}

The output of the code:
An Exception has come

With the above example:


public class myMultiCatchException{
   public static int j;
   public static void main(String args[])
   {
       for(int i=0;i<4;i++)
           try{
               switch(i){
                   case 0:
                       int zero=0;
                       j=2/zero;
                       //divide by zero exception
                       break;
                    case 1:
                        int b[]=null;
                        j=b[0];
                        //null pointer exception
                        break;
                    case 2:
                        int[] c=new int[2];
                        j=c[10];
                        //array outofBoundException
                        break;
                    case 3:
                        char ch="java".charAt(10);
                        //String index out of bounds Exception
                        break;
               }
           }
           catch(Exception e)
           {
               System.out.println("An error has occured");
           }
           }
   }
}
       

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
An error has occurred
An error has occurred
An error has occurred
An error has occurred
As Exception is the base class of all Exception classes ,hence any Exception can be caught with this approach. But we do not get any specific information about the Exception.


public class myMultiCatchException{
   public static int j;
   public static void main(String args[])
   {
       for(int i=0;i<4;i++){
         try{
             switch(i){
             case 0:
                  int zero=0;
                  j=2/zero;//divide by zero 
                  break;
             case 1:
                  int b[]=null;//not initialized
                  j=b[0];//null pointer exception
                  break;
             case 2:
                  int c=new int[2];
                  j=c[10];//Array out of bound Execption
                  break;
             case 3:
                  char ch="Java".chatAt(9);//String index out of bound 
                  break;
                  }
             }
          catch(Exception e)
          {
           System.out.println("In the testcase#"+i);
           System.out.println(e);
          }
   }
}
}
}
 

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
An error has occured
The message->/ by zero
get more info->java.lang.ArithmeticException: / by zero
An error has occured
The message->null
get more info->java.lang.NullPointerException
An error has occured
The message->10
get more info->java.lang.ArrayIndexOutOfBoundsException: 10
An error has occured
The message->String index out of range: 10
get more info->java.lang.StringIndexOutOfBoundsException: String index out of range: 10
java.lang.ArithmeticException: / by zero
at myMultiCatchException.main(myMultiCatchException.java:10)
java.lang.NullPointerException
at myMultiCatchException.main(myMultiCatchException.java:15)
java.lang.ArrayIndexOutOfBoundsException: 10
at myMultiCatchException.main(myMultiCatchException.java:20)
java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.lang.String.charAt(String.java:658)
at myMultiCatchException.main(myMultiCatchException.java:24)

Finally Block

Finally is the next pillar for exception in java tutorial.Exception handling is in fact built with try,catch and finally block. However Finally is optional.Irrespective of try and catch block,finally block gets executed.

A try will have one finally block.in finally block ,before exiting from a program,we close open files,open connections,free up some resources etc.The finally block of code will always be executed irrespective of an exception has occurred or not.

So if we put these closure lines in try or catch, there is no guarantee that these lines will get executed every time. Finally block will be disrupted if an exception occurred inside it or the system.exit is invoked before it.

Say we are trying to process a file and the file is not present in the directory. In that case the exception occurred and in finally block we are trying to close the same file which will raise one more exception.

Exception handling in java best practices also suggest to have a finally block.Exception in java interview questions may have some tricky questions.

An example for finally block:


public class DemoMyFinally{
    public static void main(String []args){
    int i=0;
    String[] myString={"Hello","Hi","GoodMorning"};
    while(i<4)
     {
        try{
        System.out.println(myString[i]);
        }
        catch(Exception e)
        {
            System.out.println("An Exception occured");
        }
        finally{
            System.out.println("Recovery started");
            i++;
        }
    }
    }
}

The output of the code:
Hello
Recovery started
Hi
Recovery started
GoodMorning
Recovery started
An Exception occured
Recovery started
On java 7 onwards we can use try with single resources ,multiple resources with an or condition using try constructor and multiple catch with or condition.

try with a single resource:

It is applicable from Java-7. So it became part of the exception in java tutorial.This is applicable for those classes which implement AutoCloseable interface. Like

BufferedReader,FileReader,BufferedWritter etc. The resource is passed as an argument to the try block. The corresponding catch block is optional for try.

Since these resources implement AutoCloseable interface,as and when try block finishes execution,the resource will be auto closed. If in case any exception occurs , they will be suppressed.We can retrieve these suppressed exception by Throwable.getSuppressed() method.


try(FileInputStream input = new FileInputStream("C:\MyTest\MyFile.txt")) {
}
 

try with a multiple resources:Multiple resources needs to be passed in try constructor separated by ; This is as per exception handling in java best practices.
Latest exception in java interview questions on java-7 on words contains this topic.


try(FileInputStream input = new FileInputStream("C:\MyTest\MyFile.txt");BufferedInputStream bufferedInput = new BufferedInputStream(input))
{
}

Modified multi catch:
Refer my previous example:


  catch(ArithmeticException e)
           {
               System.out.println("can not divide by zero");
           }
           catch(NullPointerException e)
           {
               System.out.println("A null pointer exception has occured");
           }
            catch(ArrayIndexOutOfBoundsException e)
           {
               System.out.println("Array index is out of bound");
           }
           catch(StringIndexOutOfBoundsException e)
           {
               System.out.println("String index is out of bound");
           } 
  

instead of this we can upgrade catch statement into a single line catch statement where the exceptions are written as or (||) form.


try{
}
catch(ArithmeticException ||NullPointerException||ArrayIndexOutOfBoundsException ||StringIndexOutOfBoundsException)
{
}
  

For an Exception there are six important steps that an exception handler follows:

  1. Find the problem inside try block we refer as hit.
  2. Inform the problem occurrence referred as throw
  3. Receive the problem information in catch block referred as catch
  4. Take corrective actions  for the problem referred as Handle
  5. if there is no corrective action available pass the problem statement to the calling method-referred as propagate till system level to default handler.
  6. Run post condition steps referred as finally.

These are the exception handling in java best practices.

Guidelines for Using Exceptions in Java

Exception in java tutorial also covers some guidelines.Exception handling provides a way to process synchronous errors such as divisions by zero and out-of-range array indexes. It’s not meant for handling asynchronous events such as disk I / O completions and mouse clicks and keystrokes. These guidelines are also important for exception in java interview questions.

When to use Exceptions?

you may be wondering as to how you actually decide to create and throw an exception. As a rule of thumb, create exception classes for all common exceptions that are likely to occur in multiple classes of an application. I was in your place sometimes back. I am trying to explain the rules here as per exception handling in java best practices.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 59
  • 85
  • 26
  • 89
  •  
  •  
  •  
  • 14
  •  
  •  
    273
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here