Exception Handling

Exception Handling

Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent abrupt termination of program. The term exception means exceptional condition, it is a problem that may arise during the execution of program. A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc.

When an exception can occur?
Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions).

Reasons for Exceptions
There can be several reasons for an exception. For example, following situations can cause an exception – Opening a non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and so on.

Points to be remembered:

  1. Exception: Run time errors of java program are known as exceptions.
  2. Whenever an application user enters invalid input then exceptions will be occurred (Exceptions are also known as system error messages).
  3. Whenever an exception occurred in the java program the program execution will be abnormally terminate, CPU Control comes out of the program and by default JVM generates system error messages. Which is not recommended software development?.

Exception class Hierarchy

Untitled

Types of Exceptions in java: In java programming exceptions are divided into two types they are

  1. Predefined exceptions
  2. User defined exceptions

 

Predefined Exception: Pre defined Exceptions are those which are developed by SUN Micro system and supplied as a part of jdk to deal with Universal Problems.

Some of the universal problems are

  1. Division by zero problems
  2. Invalid bounds of array
  3. Invalid formats of a number e.t.c.,

User Defined Exceptions: User Defined Exceptions are developed by java programmer and supplied as a part of their project to deal with common specific Problems some of the specific problems are

  1. Entering negative ages for human beings.
  2. Entering negative salaries for employees.
  3. Trying to deposit the negative amounts.

Hence the above types of exceptions makes us to understand for every invalid operation/action/ there exists one class and it is known as “Exception Handling classes” and whose object can stop the program execution abnormally.

Exception is categorized into 3 categories.

  • Checked Exception

The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.

  • Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.

  • Error

Errors are typically ignored in code because you can rarely do anything about an error. Example: if stack overflow occurs, an error will arise. This type of error is not possible handle in code.

Exceptions Methods:

Following is the list of important methods available in the Throwable class.

SN Methods with Description
1 public String getMessage()

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

2 public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3 public String toString()

Returns the name of the class concatenated with the result of getMessage()

4 public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.

5 public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

6 public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Exception Handling Mechanism

In java, exception handling is done using five keywords,

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

Try:

  1. It is one of the predefined block here we can write the block of the statements those will causes problems at runtime. In other words if we have any problematic statements are highly recommended to write in try block.
  2. If any exception occurs in try block then program execution is abnormally terminated control goes out from the try block and executes appropriate catch block.
  3. After executing appropriate catch block, control never come back to try block for executing the statements. Even we use return statement in the Catch block.
  4. Each and every try block must be immediately follows catch block. That is not intermediate statements are allowed between try and catch blocks.
  5. Each and every try block must contain at least one catch block. This is highly recommended to write multiple catch blocks for generating the multiple user friendly error messages.
  6. One try block can contain another try block with corresponding catch blocks. That is nested/inner try blocks can be possible.

Catch:

  1. Catch is one of the predefined block in which is used to write the block of the statements which provides user friendly error messages by suppressing system error messages.
  2. An appropriate catch block will be executed an exception occurs in the try block.
  3. At any point of time only one catch block will executed out of multiple catch blocks.
  4. Programmatically catch in catch block we can declare an object of appropriate exception and it is

            Internally referenced by JVM if an appropriate exception occurs.

EX: ArithmeticException ae=new ArithmeticException(/zero) //done by JVM

  1. In one catch block one can also write try and catch blocks.

Finally Blocks:

  1. It is one of the predefined block in which we write the block of statements which will terminates the resources of files, database which are obtained in the try block. In generally finally block contains resource relinquishing logic (terminating logic).
  2. Finally block will executes compulsorily.
  3. Writing finally block in java program is optional
  4. A finally block contain try and catch blocks.
  5. Per java program it is highly recommended to write one finally block.

 

Throws Keyword: We know that to perform every operation in every programming language including java we must perform through methods.

  1. In specific programming the methods can be classified into two types they are specific methods and common methods.
  2. Specific methods: Specific Methods are those which always deals with the specific requirements of the programmer and not suitable for the multiple programmers.
  3. Common methods: Common Methods are those which are always deals with common requirements of common programmers. Specific methods are also known as calling functions. Common methods are also known as called functions.

According to the industry standards, if any exceptions are occurring in specific functions then as a programmer we write try and catch blocks for generating the specific user friendly error messages where as if we develop any common method and if any exceptions are occurring then as a common method developer we write a throws keyword for expressing or describing the type of exceptions occurring in the common methods but not recommended to write TRY and CATCH blocks. Because as a common method developer we can’t generate specific user friendly error messages.

 Functionality of Throws (DEF): Throws is a keyword which gives indication to the calling function to keep the called function under TRY and CATCH blocks for giving user friendly error messages.

(OR)

Throws  keyword will establish the bridge or communication channel between calling function and called function.

(OR)

Throws keyword describes or express the number of exceptions occurring in the common method (Called function).

  1. If any common method followed by a keyword throws then such common methods are known as exception common methods. Otherwise it is normal common method.
  2. As a specific function developer, whenever we decide to use common method then it the responsibility of the java programmer to check whether is normal or exception method.

Java.lang.Integer

                         Public static int parseInt(String) throws java.lang.NumberFormatException

We understand the above method is not a normal method but it is one of the exception common method and recommended to place within TRY and CATCH blocks.

  • Throws keyword must be used always as a part of method handling.

Syntax for throws keyword:

Return type MethodName (list of params if any) throws exception 1,——, exception n

{

Block of statements

}

In the above syntax exception1 ——-exception n represents either predefined or user defined or both.

throw Keyword

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.

Syntax :

throw ThrowableInstance

Using try and catch

Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it.

Example using Try and catch

Output :

Divided by zeroAfter exception is handled

An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line “This line will not be executed” is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line “After exception is handled” is printed.

Multiple catch blocks:

A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.

Example for Multiple Catch blocks

 

Q) What is meant by Rethrowing exception?

 A) First function throws an exception to the second function. Second function throws the first function related exception to the third function with respective second function first function exception is known as Rethrowing exception.

For example in the previous program parseIn () is throwing NumberFormatException to division method and division method interms throws the same exception to the main() hence with respect to division method NumberFormatException is known as rethrowing exception.

Number of ways to find details about unknown exception whenever we write a java program there is a possibility of getting many number of exceptions. As a java programmer for each and every exception, we must know the predefined exception subclass. If we know the specific exception sub class names then only it is possible to display user friendly error messages. Otherwise we may come across system error messages.

As a java programmer we may not be knowing all the exception related class names in java programming but in exception handling concept we have three techniques to find out details about the exceptions. They are

  1. By using the object of java.lang.Exception
  2. By using PrintStackTrace()
  3. By using an Object of java.lang.Exception: We know that java.lang.Exception is the super class for all synchronous exceptions those are for both cheked(directly) and un cheked(in directly) . Whenever we come across Multiple unknown exceptions during the java program development, we must place those statements with in the TRY block and we need to write CATCH block in which we use an object of Java.lang.Exception. Because according the concept of dynamic binding an object of java.lang.Exception can contain the details of all unknown exceptions which are occurin in java programming. An object of java.lang.Exception displays the following details about the unknown exceptions.

 

Nested try statement

try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catchhandler for a particular exception then the outer try is checked for match.

Important points to Remember

  1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
  2. Super classThrowable overrides toString() function, to display error message in form of string.
  3. While using multiple catch block, always make sure that exception subclasses comes before any of their super classes. Else you will get compile time error.
  4. In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try, if required.
  5. Only the object of Throwable class or its subclasses can be thrown.

Try with Resource Statement

JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.

Syntax

try(resource-specification){//use the resource}catch(){…}

This try statement contains a paranthesis in which one or more resources is declare. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement, you do not have to explicitly close the resources.

throw Keyword

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.

Syntax :

throw ThrowableInstance

Creating Instance of Throwable class

There are two possible ways to get an instance of class Throwable,

  1. Using a parameter in catch block.
  2. Creating instance withnew

3.      new NullPointerException(“test”);

This constructs an instance of NullPointerException with name test.

throws Keyword

Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.

Syntax :

type method_name(parameter_list) throws exception_list{ //definition of method}

NOTE : It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their subclass.


Rules for Exception Handling

1]When child class method is throwing border checked exception compared to the same method of base class

Output:
Compilation error because the color() method of child class is throwing Exception which has a broader scope than the exception thrown by method color() of parent class.

2] When base class and child class both throws a checked exception

3] If base class doesn’t throw any exception but child class throws an checked exception

4] If base class doesn’t throw any exception but child class throws an unchecked exception.

In this example class Room is overriding the method color(). The overridden method is not throwing any exception however the overriding method is throwing an unchecked exception (NullPointerException). Upon compilation code ran successfully.

5] Java try block must be followed by either catch or finally block.

6] At a time only one Exception is occurred and at a time only one catch block is executed.

7] All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

8] For each try block there can be zero or more catch blocks, but only one finally block.

9] In nested try catch block if exception occurs outer try catch block its handled on outer catch block but if exception occurred on inner try block but inner catch is not capable to handle this type of exception its handle in outer catch block.

Exception not occurred—> outer try catch


Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

No. throw throws
1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

No. final finally finalize
1) Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Finally is used to place important code, it will be executed whether exception is handled or not. Finalize is used to perform clean up processing just before object is garbage collected.
2) Final is a keyword. Finally is a block. Finalize is a method.

User defined Exception

: User defined exceptions are those which are developed by the java programmer and supplied as a part of their project to deal with the common specific problems. Some of the common specific problems are

 

  1. Trying to enter negative ages for human beings.
  2. Trying to enter negative salaries for employees.
  3. Trying to deposit invalid amounts
  4. Trying to enter invalid password characters e.t.c.,

 

What are all the guidelines followed SUN Micro system for the development of predefined exceptions, the same guidelines followed by us for development of user defined exceptions.

 

The exception subclasses which are develop either by the java programmer or by SUN Micro system will have the nature of stopping the program execution abnormally and by default generates System error messages.

 

*Steps or Guidelines for developing user defined exceptions: In order to develop user defined exceptions as a part of our real world applications we must follow the following sequence of steps. Also followed by SUN Micro system for the development of pre defined exceptions.

 

  1. Choose the appropriate package for placing user defined exception sub classes for common access and ensure that the package statement must be first executable statement.
  2. Choose an appropriate user defined class and ensure whole modifier must be Public and class is going to be called as user defined exception sub class.
  3. Whatever the class is selected in step2 it must extends either java.lang.exception or java.lang.RuntimeException for gaining the power of exception to stop the program execution abnormally. Hence ste2 class is known as user defined exception sub class.
  4. Each and every user defined exception sub class must contain parameterized constructor by taking String as a parameter (String parameter represents nature of the message).
  5. * Each and every user defined exception Sub class parameterized constructor must call the parameterized constructor either Java.lang.Exception or java.lang.RuntimeException by using/writing super(msg) here msg represents a String parameter which contains the nature of the message. (Because the java programmer is not aware of specific exceptions and if specific exceptions are occurring in the java program those messages and specific exception details must be posted to either Java.lang.Exception or Java.lang.RuntimeException
  6. Whatever the user defined excetion sub class we are placing in the package, the class name must be given as a file name with an extension .java.

As a part of user defined exceptions application development as a real world programmer we can develop three categories of classes they are

  1. Development of user defined sub classes.
  2. Development of user defined general classes.
  • Development of user defined specific classes.

Developing User Defined Exception Sub classes: The programs NsalException.java and PsalException.java comes under the development of user defined exception sub classes.

Development User Defined General Classes: The user defined general classes will make use of user defined exception sub class for stopping the program execution abnormally.

Development of user defined specific classes: The user Defined specific class makes use of user defined class and handle the corresponding exception we make use of user defined exception sub classes.

 

Interview Question and Answers: 

What is an exception?

            An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

What is error?

            An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.

Which is superclass of Exception?

            “Throwable”, the parent class of all exception related classes.

What are the advantages of using exception handling?

            Exception handling provides the following advantages over “traditional” error management techniques:

Separating Error Handling Code from “Regular” Code.

Propagating Errors Up the Call Stack.

Grouping Error Types and Error Differentiation.

 

What are the types of Exceptions in Java

            There are two types of exceptions in Java, unchecked exceptions and checked exceptions.

  • Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.
  • Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.

 

Why Errors are Not Checked?

            A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

Why Runtime Exceptions are Not Checked?

            The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

What is the use of finally block?

      The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.

Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes

What if there is a break or return statement in try block followed by finally block?

            If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.

Can we have the try block without catch block?

            Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.

What is the difference throw and throws?

            throws: Used in a method’s signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.

A method that does not handle an exception it throws has to announce this:

  public void myfunc(int arg) throws MyException {

}

throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

To throw an user-defined exception within a block, we use the throw command:

  throw new MyException(“I always wanted to throw an exception!”);

How to create custom exceptions?

    By extending the Exception class or one of its subclasses.

Example:

class MyException extends Exception {
public MyException() { super(); }
public MyException(String s) { super(s); }
}

     Have you faced OutOfMemoryError in Java? How did you solved that?

            This Java Error interview questions is mostly asked on senior level Java interviews and here interviewer is interested on your approach to tackle dangerous OutOfMemoryError. Admit it we always face this error no matter which kind of project you are working so if you say no it doesn’t go very well with interviewer. I suggest even if you are not familiar or not faced it in reality but have 3 to 4 years of experience in Java, be prepare for it. At the same time, this is also a chance to impress interviewer by showing your advanced technical knowledge related to finding memory leaks, profiling and debugging. I have noticed that these skills almost always creates a positive impression.

 Does code form finally executes if method returns before finally block or JVM exits ?

            This Java exception interview question can also be asked in code format, where given a code with System.exit() in try block and something in finally block. It’s worth knowing that, finally block in Java executes even when return keyword is used in try block. Only time they don’t execute is when you call JVM to exit by executing System.exit(0)from try block in Jav

What best practices you follow while doing Exception handling in Java ?

This Exception interview question in Java is very popular while hiring senior java developer of Technical Lead. Since exception handling is crucial part of project design and good knowledge of this is desirable. There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of them:

          1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since NPE is most infamous of all Java exceptions, there are lot of techniques and coding best practices to minimize NullPointerException. You can check that link for some specific examples.

        2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in Exception handling because they just ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements.

         3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it improves readability of

code by removing boiler plate exception handling code

         4) Never let your database Exception flowing till client error. since most of application deal with database and SQLException is a checked Exception in Java you should consider handling any database related errors in DAO layer of your application and only returning alternative value or something meaningful RuntimeException which client can understand and take action.

         5) calling close() methods for connections, statements, and streams on finally block in Java.

    What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.

Consider if NoClassDefFoundError occurs which is something like

java.lang.NoClassDefFoundError

src/com/TestClass

does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that’s not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

 What is difference between Error and Exception?

Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

When to use Checked Exception in Java

Knowing Checked Exception is not that useful until you know how to use Checked Exception in Java. Java has often been criticized for its Checked Exception strategy, arguments given are that checked Exception adds lot of boiler plate code and makes whole class or function unreadable. Somewhat I agree with this and java also recognize this by introducing improved Exception handling mechanism in Java7 but Checked Exception does have its real purpose. Following are some scenarios where I would prefer to use Checked Exception to ensure that Code is Robust and stable:

                1) All Operation where chances of failure is more e.g. IO Operation, Database Access or Networking operation can be handled with Checked Exception.

               2) When you know what to do (i.e. you have alternative) when an Exception occurs, may be as part of Business Process.

               3) Checked Exception is a reminder by compiler to programmer to handle failure scenario.

 

Example of checked Exception in Java API
Following are some Examples of Checked Exception in Java library:

  • IOException
  • SQLException
  • DataAccessException
  • ClassNotFoundException
  • InvocationTargetException

What is Unchecked Exception in Java?

Unchecked Exception in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn’t reduce code readability and keeps the client code clean.

When to use UnCheckedException in Java

A good strategy of Exception handling in Java is wrapping a checked Exception into UnCheckedException. Since most of Database operation throws SQLException but it’s not good to let SQLException propagate from your DAO layer to up higher on business layer and client code provide exception handling you can handle SQLException in DAO layer and you can wrap the cause in a RuntimeException to propagate through client code. Also as I said earlier unchecked exceptions are mostly programming errors and to catch them is real hard until you do a load test with all possible input and scenario.

Difference between Checked and Unchecked Exception in Java

Now we have enough information to differentiate Checked Exception with Unchecked Exception:

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn’t.

2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.

3) CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.

Example of unchecked Exception in Java API

Here are few examples of Unchecked Exception in Java library:

NullPointerException

ArrayIndexOutOfBound

IllegalArgumentException

IllegalStateException

 

What is Exception chaining in Java?

Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an unchecked or RuntimeException. By the way if you are throwing new exception due to another exception then always include original exception so that handler code can access root cause by using methods like getCause() and initCause().

 What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java?

            This is Java Exception interview question was not very popular, but appears in various fresher level interviews, to see whether candidate is familiar with concept of checked and unchecked exception or not. By the way answer of this interview question is both of them are example of unchecked exception and derived form RuntimeException. This question also opens door for difference of array in Java and C programming language, as arrays in C are unbounded and never throw ArrayIndexOutOfBoundException.

Difference between throw vs throws in Java

throw and throws are two Java keyword related to Exception feature of Java programming language. If you are writing Java program and familiar with What is Exception in Java, its good chance that you are aware of What is throw and throws in Java. In this Java tutorial we will compare throw vs throws and see some worth noting difference between throw and throws in Java. Exception handling is an important part of Java programming language which enables you to write robust programs. There are five keywords related to Exception handling in Java e.g. try,catch, finally, throw and throws. Apart from difference between final, finally and finalize,  throw vs throws is one of the frequently asked Java interview question. Difference listed here will not only help you to answer this interview question but also understand concept behind throw and throws better.

1) throw keyword is used to throw Exception from any method or static block in Java while throws keyword, used in method declaration, denoted which Exception can possible be thrown by this method.

2) If any method throws checked Exception as shown in below Example, than caller can either handle this exception by catching it or can re throw it by declaring another throws clause in method declaration.

public void read() throws IOException{

   throw new IOException();

}

failure to either catch or declaring throws in method signature will result in compile time error.

3) throw keyword can be used in switch case in Java but throws keyword can not be used anywhere except on method declaration line.

4) As per Rules of overriding in Java, overriding method can not throw Checked Exception higher in hierarchy than overridden method . This is rules for throws clause while overriding method in Java.

5) throw transfers control to caller, while throws is suggest for information and compiler checking.

6) Both Checked and Unchecked Exception can be declared to be thrown using throws clause in Java.

 What is exception matching?

Ans) Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn’t find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.

What does ‘Ducking’ the exception mean?
If a method does not handle the exception but simply declares it using throws , the method is said to be ducking the exception.