digitization, transformation, binary

Learn Exception Handling in Java Quick and Fast Manner

Table of Contents

Share and Enjoy !

Exception Handling in Java

This post will cover exception in java tutorial, runtime exception in java, exception handling in java with examples, exception handling in java best practices, exception in java interview questions, and give us the guidelines that may help us to get the most of java’s Exception handling mechanism. We will be able to write a more powerful, effective java code by taking most of this post.

Exception and Error Concept Simplified in Java:

Exceptions

An Exception is an unusual or abnormal condition that occurs during the execution of the program. If Exceptions are not handled properly or taken care,the program will terminate abruptly  or provide wrong results. In other word,Exceptions are events that interrupts the normal flow of the execution.(Disruption during normal flow of execution).
class throwable is used to represent all Exceptional conditions.Exceptions are used for exceptional condition that user program can catch.We need to remember that Error  is different from Exception.Errors are used to catch at normal condition.In some cases errors are not supposed to catch and handle.They may be beyond the control of Programmers. If JVM is not able to allocate memory to create new objects ,during the program execution,the JVM will throw an error. Program will get terminated.In this situation,programmer can not handle


Java’s Exception handling brings runtime error management into object oriented world.
How do we get Exception in java? Exception in thread “main” with some details popularly known as stack trace. Now if user gets such kind of Exception,it is very tough for an user to understand the issue. Instead if we get a clear message , may be, the non technical person will never come to IT team.

Popular Exceptions are —

 

  • A network connection is lost in the middle of communication
  • Product not available
  • Can not divide by zero
  • if user inserts invalid data(Invalid username and password)
  • A file that needs to opened can not be found
  • JVM ran out of memory.

Exceptions are encapsulated into object that extends Throwable class.Like any other object we can create Exceptions on the heap using new keyword and a constructor gets called. Read here for Class Exception more.If a method throws an Exception , it must assume that it is caught and dealt with.The good part of java Exception is that it allows us to deal with the problem in one place and allows us to deal with the error in some other place.
Lets check the popular Exception generation code:

Lets observe the below code:

public class myException{
public static void divide(int x,int y)
{
int z=x/y;
System.out.println(z);
}
public static void main(String args[]){
divide(10,0);
//Exception occurs here
}
}

The output of the program will be as below:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at myException.divide(myException.java:4)
at myException.main(myException.java:8)
It is called method stack trace.
The first line says about the type of Exception-java.lang.ArithmeticException:
The first line also says the Exception message-/ by zero

And the below two lines talks about the location/package/class/method/filename where the Exception really occurred. If we observe it more details, the second line talks about where the Exception is actually occurred and how it is propagated to the calling function.
During execution when an Exception occurs an object of the respective Exception class is created and thrown in the method which causes the Exception.Now the method may choose two things:

  1. To catch the Exception and can guard the Exception against premature exit by a block of code.
  2. Pass the Exception object to the calling method.

Propagation of Exception in realtime:

——->                ——->                                         ——->
Runtime    Call                    Call                                               Call
————–Main()—————-Calling Function(1)————Calling Function(n)
System    Exception            Exception                                    Exception
<———-             <———-                                      <———-

 

We do not have a handler for any kind of Exception here.Whenever an Exception occurred , the run time environment (JRE) generates the Exception object and throws it. The moment an Exception object is thrown, further Exception steps and if it is not taken care of the Exception propagated to the calling environment. The calling environment can be either the run time system or calling method. In the above example, the Exception occurred in divide() method,as there was no handling mechanism , the Exception propagated to the calling method- main().Again the main() method did not have any Exception handling,it went to the calling environment i.e runtime. java provides a default run time handler.When runtime Exception handler receives the Exception,it shows the stack trace and terminate the program.
Exceptions are encapsulated into object that extends the throwable class and object of java.lang.Exception class.All the Exceptions belong to Exception class which is a child of throwable class.
Throwable
|
—————————————————————————–
|                                                                                                     |
Exception                                                                                      Error(Unchecked)
|
——————-

|                        |
Checked       Unchecked
Checked Exception:
1. IOException
2. ClassNotFoundException
Unchecked Exception:
1. Arithmetic Exception
2. ArrayIndexOutOfBoundException
3.NullPointerException
4.ClassCastException

The base class Exception is defined here.An Exception object can make use of the below methods of the throwable class:

MethodDescription
String getMessageReturns the description of an Exception. Example- throwable.getMessage()
Void printStackTrace()Displays the stack trace (Mostly used in debugging) Example- throwable.printStackTrace()
String toString()returns a string containing a short description of the Exception Example- throwable.toString()

Popular Exception and Error Classes are:

Runtime Exception SubClassesException Sub ClassesError Sub ClassesError Sub Classes
ArithmeticExceptionClassNotFoundExceptionClassCirculatoryErrorAbstractMethodError 
ArrayOutOfBoundsExceptionDataFormatExceptionClassFormatError
ArrayStoreExceptionIllegalAccessExceptionOutOfMemoryError
ClassCastExceptionInstantiationExceptionIllegalAccessError
IllegalArgumentExceptionInterruptedExceptionIncompatibleClassChangeError
IndexOutOfBoundsExceptionNoSuchMethodExceptionInstantiaonError
NegativeArraySizeExceptionCloneNotSupportedExceptionLinkageError
NullPointerExceptionNoSuchFieldExceptionNoClassDefFoundException
NumberFormatExceptionInvocationTargetExceptionNoSuchFieldError
SecurityExceptionPropertyVetoExceptionNoSuchMethodError
StringIndexOutOfBoundExceptionServerNotActiveExceptionStackOverFlowError
UnknownServiceExceptionUnknownHostExceptionThrowable
IllegalThreadStateException SocketExceptionUnknownError
IllegalMonitorStateException ProtocolExceptionUnsatisfiedLinkError
EmptyStackException InterruptedIOExceptionVerifyError
NoSuchElementExceptionMalformedURLExceptionVirtualMachineError
IOExceptionThreadDeath
FileNotFoundExceptionStackOverFlowError
EOFExceptionInternalError  

 

Checked Exception:

Checked Exceptions should be either declared in the throws clause of an method or should be handled inside a try catch block. or the statements(including method calls)that can throw the exception are inside a method that has a throw clause in the header.The throws clause contains a matching exception type.(Exceptions and it’s sub classes are checked Exception.Checked Exceptions are verified at compiletime and must be handled or thrown.They are also known as compile time Exceptions.These Exceptions should not be ignored at the time of compilation.An Exception if sub class of Exception but not RuntimeException becomes checked Exception.
Example:-


File file=new File("path of the file");
 

if we try to compile the above code,we will get the following exception:
Unreported FileNotFoundException must be caught or declared to be thrown

Unchecked Exception:

Unchecked Exceptions are not mandatory to either declared or handled. They are ignored at compile time by java compiler.Errors and Runtime Exception and it’s sub classes are unchecked Exception. RuntimeExceptions are used to indicate programming error such as logic errors or improper use of an API ,programming bugs etc.If we create our custom exception and extend to RuntimeException instead of Exception,our custom Exception becomes Unchecked. It is dangerous if we do not know what we are doing. Hence best practice is to make custom Exception extending to Exception.


int num[]={1,2,3}
System.out.println(num[5]);
 

This code will compile fine but fails at runtime.
Exception details:
Exception in Thread “main”
java.lang.ArrayIndexOutOfBoundsException

The purpose of Exception handling is to provide a means to detect and report an “Exceptional circumstance “,so that a proper action can be taken.
The process is as follows:

Process-I

  1. Find the problem(Hit the exception)
  2. Inform that an exception/error has occurred (throw the exception)

Process-II

  1. Receive the error information(Catch the exception)
  2. Take corrective actions(Handle the exception)

Error: 

Errors are wrong/mistakes that can make a code go wrong.An error may produce an incorrect output or may terminate the execution.Errors can abruptly stop an execution or may crash the system.Errors can be divided into two catagories:

  • Compile time error
  • Runtime error

Compile time errors:

All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile time error.Whenever compiler displays an error,it will not create the .class file.Hence it is necessary to fix all of them to successfully compile and get the .class file.
Once the compile time error occurs ,we need to go to the appropriate lines ,correct the errors and recompile the program.We should generally consider the earlier errors as the major source of our problem.After we fix such an error,we should recompile to look for other errors.
Compile time errors are mainly due to the following:

  • Typing mistake
  • Missing semicolons
  • Missing or mismatches of brackets in classes or methods
  • Misspelling of identifiers or keywords
  • Missing double quotes in String
  • Use of undeclared variables.
  • Incompatible types in assignments/initialization.
  • Bad references to objects
  • Use of ‘=’ instead of ‘==’
  • Javac: command not found.(Due to either java is not installed or path issue)

Runtime errors:

Error are referred as Runtime error and its sub classes are used for serious errors from which programs are not suppose to recover.They are not at all Exceptions. Errors are generally ignored during compilation time.
Exp-out of memory error.
If compiler displays an error it will not create a .class file.While runtime error occurs,program will stop execution after displaying error message.

Runtime errors are mainly due to the followings:

  • Dividing an integer by zero.
  • Accessing an element that is out of bounds of an array or String.
  • Trying to store a value into an array of an incompatible type or class.
  • Trying to cast an instance of a class to one of its subclases.
  • Passing a parameter that is not a valid range or value for a method.
  • Trying to illegally change the state of a thread.
  • Attempting to use  a negative size for an array.
  • Using a null object reference as a legitimate object reference to access a method or variable.
  • Converting invalid String to a number.
  • Accessing a character that is out of bounds of a String. etc

 

Why force Checked Exceptions thrown by a method to be caught but not Unchecked Exception?

Checked Exceptions thrown by a method are part of the public programming interface.Those who invokes the method must be aware of them and should  decide what to do with them.On the other hand, unchecked Exceptions are result of programming problem. It is usually not possible to recover from those problems.There could be numerous possibilities for Unchecked Exceptions,trying to cover all of them will reduce that code clarity.

Rule of Thumb while designing the public API that throws Exception:

  1. If the API user can take some meaningful action from the information available in the Exception object,We need to declare the Exception as checked.
  2. if the API user can not do anything meaningful after the Exception is thrown,We need to declare it as Unchecked Exception

Rule of Thumb with Exceptions Across Layers:

We need to make sure implementation of specific lower level exception should never propagate to higher levels(Low level Data access exception should not propagate to higher level like business level as it does not make any sense there)
Note:

  • A statement in a method can throw an exception that is not matched by a catch clause.This includes situations in which the statement throwing the exception is not even inside a try catch block.When this happens , execution of the program jumps out of the method that contains the faulty statements.Execution jumps back to whatever code called the method in the first place.
  • A method can name more than one exceptions type in its throws clause. We need to use comma to separate these exception types.

Exception Handling in Java:

The below guide will help us to understand exception handling in java with examples. Exception handling is a programming technique that can detect things that can go wrong and respond by creating a new Object. (In the official terminology the code is said to be throwing an exception).

The new object an instance of the exception class is passed. Some program is intended to catch the exception. When the exception is caught, the program executes some recovery code, buries the exception and moves back to the normal statement.

The point where the problem occurs, we may not know what to do with it. At that point we may not continue further, we stop and either resolve the problem in the current context or if we do not sufficient information to make a decision, we hand it over to the higher context.

In the next few paragraphs, we will learn exception handling in java best practices.

With Exception handling in place, reading writing and debugging code becomes much cleaner as Exceptions clean up error handling code. Instead of checking for a particular error and dealing with it in multiple places, we can handle the Exception in only one place. Whenever an exception is thrown from code, we need to handle the exception. Handling the exception can be done in two ways:

  1. Using try-catch block
  2. Using throws keywords.

Using the try-catch block we can handle the exceptions instantly. Any error-prone code or sensitive operation should be put inside try-catch block. In this post, we will look into details of the try catch block.

By using throws keyword we pass the exception to the caller method to handle or to pass again to Java’s default exception handling. The throws keyword is written in detail here.

This is the basic exception handling in java with examples. This is a very important topic for the exception in java interview questions.

what if we do not handle an exception:

This is a very important part of the exception in java tutorial. If we do not handle the exception, it propagates to the higher context. If there is no exception handling mechanism, again it propagates to the higher context and so on. Finally, it reaches the default exception handler of JVM. It prints the stack trace and terminates the program. This is not exception handling in java best practices.


public class myException{
public static void main(String []args){
myFunction(2,2);
myFunction(2,0);
myFunction(4,2);
}
private static void myFunction(int x,int y){
int z=0;
z=(int)x/y;
System.out.println("result of division"+z);
}
}

The output of the code:
$javac myException.java
$java -Xmx128M -Xms16M myException
result of division1
Exception in thread “main” java.lang.ArithmeticException: / by zero
at myException.myFunction(myException.java:10)
at myException.main(myException.java:5)

A the second case the exception has occurred. As there is no exception handling mechanism, the exception is propagated to the calling function main.

Main also does not have any exception handling, as a result, the exception is handed over to the default handler. The default handler provides the stack trace and terminates the program.so if we handle the exception the execution will not stop in between. This concept may be asked in Exception in java interview questions.

try-catch block:

The basic building block for an exception in java tutorial is the try-catch block. A try statement is an assembly of a try-catch clause. Every catch statement is like a little mini method with its parameter list. The parameter list always has an exception type name and then a parameter.

The scope of try is ordinary and the block is preceded by try keyword .try is the place where an exception might occur and catch is the place where we catch that exception and handle it. It is always better to write a try block for each risky method.

A method thus catches an Exception using a combination of the try and catch block. The code placed inside of the try and catch is referred to as protected code. This approach makes code lengthy and not read friendly.The second approach is to put all risky code inside a single try block. This will be readable(as per exception handling in java best practices).

It is the developer’s choice. However, try-catch tries to handle the Exception in the current context. Below the guidelines for an exception in java tutorial or exception handling in java with examples. The exception handling in java best practices are-

  • A try block must immediately be followed by one or more catch statements and a final finally block…
  • There may be one or more lines of code that will generate the Exception.
  • When an exception occurred or thrown inside of the try block, the control immediately jump to the catch block and the first matching catch block is executed. The remaining statements in the try block are skipped.
  • When an exception is caught and handled by the catch block, the execution control does not jump back to the point where the exception occurred i.e the try block.
  • If no matching catch block is found, the exception is unhandled and will propagate to the calling method to default handler and the program will terminate.
  • If no exception is thrown from try block the catch block never gets executed, the control goes to finally block(if available) or next line of code to execute.

Each catch clause is similar to a method that takes one and only one argument of a particular type. Sometimes we never use the identifier as the type of Exception gives us enough information to deal with the Exception, but the identifier must be there.

The handler catch block must appear directly after the try block. If the exception is thrown, the Exception handling mechanism goes hunting for the first handler with an argument that matches the type of the Exception.

Then it enters into the catch block and the Exception is considered handled. If no matching catch block is found, it still hunts for the matching Exception, Only the matching clause executes.

It is not like the Switch statement where we need to break to prevent remaining Exceptions from Executing. Once the catch clause executes the code, the control comes out of the whole try-catch block.

Inside try block, there can be many methods or statements that generate the same Exception, in that case, one handler is enough to catch it.

While hunting for proper Catch clause the JVM follows the below:

  1. The clause’s parameter type is the same as the type of exception that was thrown.
  2. The clause’s parameter type is a superclass of the Exception type.

the syntax for try-catch in exception in java tutorial. Guide on exception handling in java with examples. This portion is very important for an exception in java interview questions.

Single catch:


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type obj)
{ 
statements that handles the exception or Exception handler
} 

real-time example:

It is very important to understand a real-time example (exception in java tutorial) or exception handling in java with examples


public class myException{
public static void main(String []args){
myFunction(2,2);
myFunction(2,0);
myFunction(4,2);
}
private static void myFunction(int x,int y){
int z=0;
try{
z=(int)x/y;
}
catch(ArithmeticException e)
{
System.out.println("Can not divide by zero!!");
}
System.out.println("result of division"+z);
}
}

The output of the code:
$javac myException.java
$java -Xmx128M -Xms16M myException
case-1
result of division1
case-2
Can not divide by zero!!
result of division0
case-3
result of division2

Also, we have one keyword called finally which takes care of the recovery or post exceptional steps:

try-catch and finally block:


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type obj)
{
statements that handles the exception or Exception handler
}
finally
{ 
//recovery code or post exception steps 
} 

Multiple catch statements:

Exception in java tutorial is not completed without this section. This is required when the real-time we may deal with different exceptions. When an exception is thrown, the exception handler looks through the nearest handler in the order they are written to find a proper match.

If the handler gets a perfect match the catch block is executed, ignoring the remaining catch blocks.Let’s see exception handling in java with examples.A very important aspect for an exception in java interview questions.


try{
statements that cause exception or Exception object creator
} 
catch(Exception_type1 obj)
{
statements that handles the exception or Exception handler
}
catch(Exception_type2 obj)
{
statements that handles the exception or Exception handler
}
catch(Exception_type3 obj)
{
statements that handles the exception or Exception handler
}
....
....
....
catch(Exception_typeN obj)
{
statements that handles the exception or Exception handler
}
finally
{ 
//recovery code or post exception steps 
} 

real-time example:

Let’s see one more exception handling in java with examples and 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"))
   //can change to a[0] to test the second condition 
    System.out.println("hi");
    if (myString.equals("hello"))
    System.out.println("true");
}
catch(NullPointerException e)
{
System.out.println("A null pointer exception is found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("index out of bound");
}
}
}

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
index out of binding
if we change to a[2] to a[0]
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
A null pointer exception is found
let’s see exception handling in java with examples with one more 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(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");
}
}
}
}

The output of the code:
$javac myMultiCatchException.java
$java -Xmx128M -Xms16M myMultiCatchException
can not divide by zero
A null pointer exception has occurred
The array index is out of bound
String index is out of bound

While working with multiple catch statements,we need to be careful about the order of the Exception class.

In case, in the catch statement if a higher (placed higher in the Exception hierarchy) order exception is mentioned before a lower(placed lower in the Exception hierarchy ) order, then the java runtime picks up the higher exception as it has been placed higher in the catch statement or as it appears first.

The lower order is ignored. It produces an unreachable code or an error.Let’s see exception handling in java with examples


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");
           }
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");
}
}
}
}

See here the Exception the superclass is mentioned first in the catch block.

As it is placed in the higher in the exception hierarchy the java runtime will always refer to the Exception class even though specific lower-order (placed lower in the exception hierarchy).

As a result, we get errors:
the output of the code:
$javac myMultiCatchException.java
myMultiCatchException.java:35: error: exception ArithmeticException has already been caught
catch(ArithmeticException e)
^
myMultiCatchException.java:39: error: exception NullPointerException has already been caught
catch(NullPointerException e)
^
myMultiCatchException.java:43: error: exception ArrayIndexOutOfBoundsException has already been caught
catch(ArrayIndexOutOfBoundsException e)
^
myMultiCatchException.java:47: error: exception StringIndexOutOfBoundsException has already been caught
catch(StringIndexOutOfBoundsException e)
^
4 errors

Catch multiple exceptions with single catch statements:

It is one of the important aspects of exception in java tutorials.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 stated catch(Exception e), all exceptions will be trapped here.Let’s see exception handling in java with examples. This is one of the exception handlings 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 suggests having a finally block. Exception in java interview questions may have some tricky questions.

An example of 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 occurred
Recovery started
On java 7 onwards we can use try with single resources, multiple resources with an or condition using try constructor and multiple catches with or condition.

try with a single resource:

It is applicable to Java-7. So it became part of the exception in java tutorial. This is applicable for those classes which implement the 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 a 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 exceptions by the Throwable.getSuppressed() method.


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

try with multiple resources: Multiple resources need 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))
{
}

The modified multi-catch:
Refer to 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 a hit.
  2. Inform the problem occurrence referred to as throw
  3. Receive the problem information in catch block referred to as catch
  4. Take corrective actions  for the problem referred to 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 the default handler.
  6. Run postcondition steps referred to 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 an exception in java interview questions.

When to use Exceptions?

you may be wondering as to how you 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.

To deal with simple errors that are likely to occur only in individual methods, try not to create an exception class. we can use an if statement in most cases to trap these types of errors.

Let’s look into an example:

try{
System.out.println (myString.toString ();
}
catch (NullPointerException e){
System.out.println ("myString is null!");
}

In this case, it is an overkill for the Exception handling. The simpler form would be:

if (myString! = null){
System.out.println (myString.toString ();
}
else
System.out.println ("myString is null");
}

When we will not catch an exception or throw exceptions?

When we call any method that throws a checked exception, we must either throw the exception or catch it. If we decide that we can not handle the exception in the method where it occurs, write a throw statement to send the exception up to the calling method, which must then either handle it with an exception handler or throw it up to its calling method.

The following set of examples shows how we must either catch or throw a checked exception, to avoid compiler errors.

The first example shows code that throws an IOException. The statement in the method getFileLength may throw an IO exception when it calls the constructor of the RandomAccessFile class.

Also, the statement that calls the length method of the RandomAccessFile object may also throw an IOException. we so specify the throws clause in the declaration for the getFileLength method to trap IOException.Let’s see exception handling in java with examples

public static long getFileLength () throws IOException{
RandomAccessFile in = new RandomAccessFile ("mytext.dat", "r");
long length = in.length ();
return length;
}

Our next example shows the code for a method that calls the getFileLength method. Since we already know that the getFileLength method call throws an IOException error, our new method must either handle the IO Exception or throw it. Our example here shows how to handle the IOException by catching it with a try statement: Let’s see exception handling in java with examples-

public static int getRecordCount(){
try{
long length = getFileLength(); // this may throw an IOException
int recordCount = (int) (length / /RECORD_SIZE);
return recordCount;
}
catch (IOException e) // this will catch the IOException
{
System.out.println("IO Exception!");
return 0;
}
}

The next example shows how a method can call the getFileLength method without catching IOException. Instead, it throws the exception. Let’s see exception handling in java with examples-

public static int getRecordCount() throws IOException
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}

The getRecordCount method here includes a throw clause, which ensures that any IOException is thrown up to the calling method.

Our next example shows what happens when we do not catch an exception or throw it.let’s see exception handling in java with examples-

public static int getRecordCount()
{
long length = getFileLength(); //this may throw an IOException
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}

Since our code fails to catch or throw a checked exception, we’ll receive a compile error:

MyExceptionTest.java.26: unreported exception java.io.IOException;

When we should catch or declared to be thrown?

Early adapter mechanism:

It is a smart thought to fuse special case taking care of into our applications from the get-go before we even begin programming. That is, we should do this at the plan organize, as it gets a lot harder to do it in the wake of executing our applications.

Do not ignore an exception

Notwithstanding whether we are managing a checked or an unchecked exception, absolutely never disregard the exemption.

we generally ignore exception by the following manner:

try {...} catch (SomeException e) {}

The unfilled catch block implies that the exception is just disregarded – it’s not correct. we would prefer not to do this in our projects. At the base, on the off chance that we should incredibly overlook the exemption, put a remark disclosing why we needed to disregard the special case.

we can utilize printStackTrace to yield a basic mistake message to let us know there was an issue. On the off chance that we overlook the exception, as a result of a condition that we have anticipated, it implies that the program will keep running on in spite of the mistake.

Notwithstanding, we’re going to risk a total program disappointment not far off when conditions change. If we spread the exception out, we can guarantee that the program bombs rapidly and catches data that encourages us to fix the mistake.

Exception Handling for every line? Not a good idea

The objective of exception handling is to clear up projects – do whatever it takes not to utilize a try, catch, finally component for each potential exception creating the line.

A straightforward procedure is to encase a lot of code inside the try block and determine numerous catch blocks to represent every single imaginable exception. End the entire thing with a finally block on the off chance that we have to discharge any assets held by the program.

Regardless, abstain from setting try, catch, finally every statement that may toss an exception. we will probably utilize exception handling to expel error handling code from the primary program code.

Keep up Failure Atomicity

Continuously endeavor to guarantee that when an item tosses an exception, the object keeps on staying in a well-characterized and usable state.

In a perfect world, even after a strategy flops because of an exception, the object ought to be left in the state it was before the method was conjured when a method can do this. it’s said to have the property of failure atomicity.

How to keep up Failure Atomicity?

Below are the ways on how we can keep up the Failure Atomicity.

  • Design Immutable Objects
  • Check Parameters for Validity before the Operation
  • Attempt to Execute the Code before we Modify the item
  • Intercept the Failure
  • Perform Operations on a Temporary Copy of the Object
  • Collect Failure Details
  • Provide accessor methods for all exceptions, especially for checked exceptions.
  • Use Standard Java Exceptions
  • Document All of a Method’s Exceptions

Design Immutable Objects

The simplest method to accomplish failure atomicity is by structuring immutable Objects. Even though when we make an object we can change its contents, every so often, it’s a smart thought to make objects whose contents can not be changed after creation.

An object, for example, is called an immutable object and it’s class, an immutable class. A genuine precedent is the String class, which is unchanging. we get programmed failures atomicity when an object is changeless(immutable), because the condition of an object can not be adjusted after we make the object.

Check Parameters for Validity before the Operation

If we are stuck with mutable objects, the best way to attain failure atomicity is to execute a check to the validity of parameters before the program commences the alteration of an object.

The initial size test ensures that the procedure can do two things in regards field in a constant state attempts field in a constant state it’ll field in a constant state can do this while leaving the dimension field in a consistent state. Otherwise, the attempt to pop the element from an empty stack will leave the dimension field in a state that is an inconsistent state for the thing to be in.

public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}

Attempt to Execute the Code before we modify the item

we can write our programs during a method wherever the code that’s vulnerable to a possible exception, is run before any code that modifies an object.

A decent example would be wherever we wish to add a component to a TreeMap, whereby the new part should be compared mistreatment the TreeMap’s ordering.

If our code attempts to feature an incorrect sort part, it’ll fail once a pursuit for the part within the tree is created, before the tree is changed.

Intercept the Failure

Another strategy to realize failure atomicity is to place in code that intercepts a failure that happens throughout associate degree operation, and that rolls back the object’s state to what it had been before the operation began. This strategy is usually adopted once modifying disk-based mostly information, that is, the information contained in a very computer database, for instance.

Perform Operations on a Temporary Copy of the Object

we can limit state changes created to associate degree object by dynamical a brief copy of the object. we replace the contents of the object with the temporary copy once we complete the process operations. If for a few reasons, the process work (say, a sort) finally ends up failing, no hurt is finished to the initial object, as we are operating with simply a duplicate of the thing.

Collect Failure Details

If we are troubleshooting simply consistent failure, it’s no massive deal whether or not we are grouping elaborated failure data. once handling exceptions that aren’t simply consistent, our exception’s toString() method must capture adequate details concerning the failure – to assist diagnose and fix the failure.

When an exception happens, our details message of exception ought to capture these values of all parameters and values that contributed to the exception. If our error message merely states IndexOutofBoundException, it’s solely of restricted use and will, or may not, assist us to fix the information downside. If on the opposite hand, our detail message for the IndexOutofBoundException contains the lower and higher bounds and also the index value, we’ve got one thing significant in our hands with that to proceed towards a fix of the failure condition.

Since the stack trace of the exception invariably contains the precise file and line range that threw the exception, we do not like loads of data concerning the ASCII text file in our exception messages. to make sure that our exceptions invariably contain adequate failure details in their details message, use one in every one of the constructors.

This is very important while learning exceptions in java tutorials.

An example:

/**
* Construct an IndexOutOfBoundsException.
*
* @param lowerBound the lowest legal index value.
* @param upperBound the highest legal index value plus one.
* @param index the actual index value.
*/
public IndexOutOfBoundsException(int lowerBound, int upperBound,int index) {
// Generate a detail message that captures the failure
super("Lower bound: " + lowerBound +", Upper bound: " + upperBound +", Index: " + index);
// Save failure information for programmatic access
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.index = index;
}

Provide accessor methods for all exceptions, especially for checked exceptions.

it’s typically helpful to supply accessor method to capture details concerning specifically why a failure happened. within the case of the instance simply shown, we can, for instance, offer accessor method for lower bound, upperBound and index. it is vital that we simply offer such an accessor method for all cases possible.

Use Standard Java Exceptions

The Java platform offers an inbuilt set of unchecked exceptions which can handle most of our exception mechanism.It is best to use these inbuilt exceptions before we get away writing our custom exceptions.

Different programmers are conversant in these preceding exceptions and, therefore, they’ll simply perceive our code. Also, since we will be utilizing simply a group of basic exception categories and not an entire bunch of custom exceptions, our programs would like less time to load.

Document All of a Method’s Exceptions

Spend the required time to completely document all exceptions thrown by every methodology in the associate application. Declare all checked exceptions singly and use the Javadoc tag @throws to document the conditions underneath that every one of the exceptions will be thrown.

It is important that we simply do not constitute the unhealthy habit of declaring that away throws some super-category of multiple exception cases that the tactic is ready up to throw. meaning that we simply need not declare a way that will throw the generic exception categories Exception or Throwable!

Exploitation generic exceptions would possibly handle the exception o.k., however, it keeps us from understanding the precise error that caused the exception to be thrown.

So, in a nutshell, we must try to document every single exception that can potentially be thrown by each method in a program.

Take care to document each checked and unbridled exceptions. Since unbridled exceptions commonly represent programming errors, documenting them will keep us from avoiding those errors. we will be able to use constant Javadoc tag @Throws to document unbridled exceptions, as is that the case for checked exceptions.

If multiple ways during a category will throw a constant exception, we will document the exception once within the class’s documentation comment. this is often rather more economical than documenting the exception severally for every one of the ways. The interviewer may cross question here-part of exception in java interview questions.

Throw early catch later principal

As a java developer, we need to follow throw early and catch later principal.

 

Few standard Exceptions: Good to know for an exception in java interview questions

How We Lose Exception Information in Java?

This is also a very important aspect of exception in java interview questions as well as an exception in java tutorial. We can also throw a different Exception than one we caught. Once we do that we get a similar effect as when using fillInStackTrace().The original information of the site of Exception is lost. The information we will have the new Exception from the position we throw the Exception.

I have written the throw keyword and its functionality in detail.
let us check the code to see exception handling in java with examples. This is exception handling in java best practices.


public class RethrowNew{
public static void main(String []args){
try{
myMethod();
}
catch(Exception e)
{
System.out.println("Caught in main");
e.printStackTrace();
throw new NullPointerException("From main");
}
}
public static void myMethod() throws Exception{
System.out.println("Originatring from myMethod()");
throw new Exception("from myMethod()");
}
}

The output of the code:
$javac RethrowNew.java
$java -Xmx128M -Xms16M RethrowNew
Originating from myMethod()
Caught in main
java.lang.Exception: from myMethod()
at RethrowNew.myMethod(RethrowNew.java:16)
at RethrowNew.main(RethrowNew.java:5)
Exception in thread “main” java.lang.NullPointerException: From the main
at RethrowNew.main(RethrowNew.java:11)
The final Exception only knows that it has come from the main() method, not from myMethod(). Throwable is not necessary for any of the Exception operations. We never have to worry about cleaning up the previous Exceptions or any of the Exception. As they are created by the keyword new, the Garbage collector will automatically clean them.

Difference Between throw and throws keyword in Java

In the below let me write throw and throws in details Furthermore I will discuss the difference between the two keywords in java.

Throw Keyword Simplified in Java

Exceptions occur when some predefined exceptional events occur in a program. Sometimes it is ok to handle predefined Exceptions but sometimes it is reasonable and convenient to define our Exceptional events. The throw keyword is used to create our own and new Exception which can be thrown to the catch block. In java, throw keyword is used by which the user can throw an exception of his/her own, instead of the automatic Exception object generated by java during runtime.

Below steps happens when we throw an exception:

  1. The Exception object itself is created, in the same way, that any java object is created on the heap with a new keyword. In general, it is not there under normal program execution and the constructor is called for that object. The object is returned from that method.
  2. The current path of the Execution (the original one that was not continued) is stopped and the handle for the Exception object is ejected from the current context.
  3. At this point the Exception handling mechanism takes over and begins to look for an appropriate place is the Exception handler, whose job is to resolve from the issue.
  4. by throwing we can send information about the issue into a larger context by creating an object representing our information and throwing it out of our current context. This is called throwing an Exception.
  5. This throws the Exception allows us in the current context, abdicate responsibilities and it is handled somewhere else.

Once we throw the handle of the Exception, all further catch clauses for the same try block are ignored and throw causes the Exception to go to the next higher context for handling. Also every information about the Exception is preserved. So that the handle at the higher context that catches the specific Exception type can Extract all information from the Object.
The syntax is :


Exception e =new Exception();
throw e;
//e is new Throwable subclass
 

Any object of type throwable can be thrown. Exceptions also accept a message for themselves.


throw new Exceptioon("Here is my Message");
 

Having Exceptions with custom message increases the readability of the application. It also helps in debugging.
Rethrowing an Exception:
It is also possible to rethrow an Exception if we want that we just caught using catch block. As in the catch block, we simply have the handle of the current Exception, we can rethrow.

catch(Exception e)
           {
               System.out.println("An error has occured");
               throw e;
           } 

An example of throw:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
} 

The above code will throw an Exception if the divisor is zero.

How a user can generate his Exception using throw:

public static void main(String args[])
{
try{
myDemo();
}
catch(Exception e)
{
System.out.println("Exception thrown by MyDemo is caught here");
}
static void MyDemo()
{
try{
throw new InterruptedException("An Interrupted Exception Occurred");
}
catch(InterruptedException e)
{
throw e;
}
}

Pure user-defined Exception:
Beside regular java Exceptions, we can create our Exception called custom exception. They make the code flexible and manageable.
we need to create an Exception class:

public class MyDivisionException Extends Exception
{
//create a parameterized constructor
public MyDivisionException(String message)
{
super(message);
}
}

then the below code:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
}
 

can be modified as:

public static void divide(int x,int y) throws MyDivisionException{ 
if(y==0)
throw new MyDivisionException("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
} 

How to rethrow of Exception preserve the information about the Exception:
If we rethrow the current Exception, the information about the Exception is preserved i.e the origin of the Exception instead of the place where we rethrew it. If we want to know the new stack trace information we can use fillInStackTrace() which returns an Exception object that is created with old Exception by appending the current stack information.

public class MyRethrowExample{
     public static void main(String []args) throws Throwable{
        try{
            methodOne();
        } 
        catch(Exception e)
        {
            System.out.println("Caught in main()");
            e.printStackTrace();
         }
    }
    public static void methodOne() throws Throwable{
        try{
            methodTwo();
        }
        catch(Exception e)
        {
             System.out.println("Caught in methodOne()");
             e.printStackTrace();
            // e.fillInStackTrace();
             throw e;
        }    
    }
    public static void methodTwo() throws Exception{
             System.out.println("Originating at methodTwo()");
             throw new Exception("Thrown from methodTwo()");
     }
 }
 

the output of the code:
$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
Explanation:
the stack trace always remembers it’s the original point of origin, no matter how many times the exception is rethrown.

Once we enable the e.fillInStackTrace(); the output is :

$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:26)
at MyRethrowExample.methodOne(MyRethrowExample.java:14)
at MyRethrowExample.main(MyRethrowExample.java:4)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodOne(MyRethrowExample.java:20)
at MyRethrowExample.main(MyRethrowExample.java:4)
Explanation:
Because of fillInStackTrace() , new point of origin of Exception,The class Throwable must appear in the Exception specification for methodOne() and main().fillInStackTrace() produces handles to a throwable object .

throwable is the base class of Exception but it may so happen that we may get an object that is throwable but not an Exception,so the handler of Exception in main() may miss it.To make sure everything is in order,the compiler forces an Exception specification for throwable.

Throws Keyword Simplified in Java

Throws keyword is used to indicate that a method may throw one or more exceptions that are defined in the method header or signature. For cases where the exception handling is mandatory for those cases, the method must announce the throws clause in the definition. The caller of the method may choose to handle that exception or can throw it again. So handling this exception is optional.

Handling every exception is a very tedious job and may hinder the coder’s output. If we do not handle the exception in a try-catch block, we can throw the exception to the calling method. If either of the two is not done compiler will throw an error. The idea behind enforcing this rule is that as a programmer, we should aware that a piece of code be risky and throws some exceptions.
By throws keyword, a designer of a method may throw any number of exceptions separated by comma(,). By throwing an exception, we can propagate and handle the exception is somewhere else in the code.

The syntax for throws is given as :

method(argumentList) throws ExecptionType1,ExceptionType2,....,ExceptionTypeN
{
} 

like:

void processMyArray(int A[])throws NullPointerException,ArrayIndexOutOfBoundsException,ArrayStoreException
{
} 

An Example:

pulic static void divide(int x,int y)throws Exception{
if(y==0)
throw new Exception("The divisor can not be Zero");
int z=x/y;
} 

In the above code, there is no try-catch block to safeguard the potential risky code. Instead, we throw an exception from here and the signature of the method says it can throw an Exception. In case if there is any Exception is created, the object will be propagated to the calling method. The calling method (maybe main). The calling method should handle the exception.

public static void callerMethod()
{
try{
divide(10,0);
}
catch(Exception e)
{
}
}
 

The caller method does not handle the Exception and may choose to throw it again.

public static void callerMethod() throws Exception
{
divide(10,0);
} 

In cases, where some states in the body of a subroutine that can throw the exception by using throw statement(throw an exception directly), like our previous divide by zero examples, or it could be a call to a method that can throw an exception.

In both cases, the exception must be handled. However, it is good to handle the exception for any exception that is not a subclass of Error or RuntimeException. Exceptions that require mandatory handling generally represent conditions that are outside the control of the program.

Besides both serve different purposes. The difference table is given below:

Sl Nothrowthrows
1a throw is used to create a new Exception object and throw it.It is used in method definition to declare that a risky method is being called and

the method may throw the specified exception.

2Using throw we can only throw one Exception typeusing throws we can declare multiple Exceptions
3Example-throw new IOException (“Can not open Connection”);Example- throws IOException, ArrayIndexBoudException

An example of throws and throws of custom Exception.

//custom exception class

 class MyFirstException extends Exception {
public MyFirstException() {super();}
public MyFirstException(String msg) {super(msg);}
}
 class MySecondException extends Exception {
public MySecondException() {super();}
public MySecondException(String msg) {super(msg);}
}
 class MyFisrtSubException extends MyFirstException {
	 public MyFisrtSubException() {super();}
	 public MyFisrtSubException(String msg) {super(msg);}
	 }
//save it to MyFirstException.java

The actual implementation of the code:



public class MyExceptionThrowTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
      int x;
		try{
			x =Integer.parseInt(args[0]);
			}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("specify an argument");
			return;
		}
		catch(NumberFormatException e)
		{
			System.out.println("specify an integer argument");
			return;
		}
		myFirstMethod(x);
	}

	private static void myFirstMethod(int x) {
		// TODO Auto-generated method stub
		try {
			mySecondMethod(x);
		}
		catch(MyFirstException e) {
			if(e instanceof MyFisrtSubException)
			{
				System.out.println("MyFirstSubException");
			}
			else
			{
				System.out.println("MyFirstException");
				System.out.println(e.getMessage());
				
			}
				
		}
	}

	private static void mySecondMethod(int x) throws MyFirstException {
		int res;
		try {
		System.out.println("x"+x);
		res=myThirdMethod(x);
		// TODO Auto-generated method stub
		}
		catch(MySecondException e)
		{
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("\n");
		}

}

	private static int myThirdMethod(int x) throws MyFirstException, MySecondException {
		// TODO Auto-generated method stub
		switch (x) {
		case 0: throw new MyFirstException("No input");
		case 1: throw new MyFisrtSubException("no input at second");
		case 50: throw new MySecondException("input too high");
		default: x=x*x;
		}
		
		return x;
	}
}


The output:
if no argument is given – the console message-specify an argument
if the argument is type float like 4.3- the console message-specify an integer argument
if the argument is type integer and value is 50- the console message-x50
input too high

This is what I have gathered on the exception in java tutorial and exception in java interview questions. Hope you enjoyed my article.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *