1. What is Exception in Java?

Exception is an error event that can happen during the execution of a program and disrupts it's normal flow. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.

Whenever any error occurs while executing a java statement, an exception object is created and then JRE tries to find exception handler to handle the exception.

If suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then application throws the exception to runtime environment and JRE terminates the program.


  2. How are the exceptions handled in java?

When an exception occurs the execution of the program is transferred to an appropriate exception handler. The try-catch-finally block is used to handle the exception.

The code in which the exception may occur is enclosed in a try block, also called as a guarded region.

The catch clause matches a specific exception to a block of code which handles that exception.

And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block.


  3. What is Runtime Exception or unchecked exception?

Runtime exceptions represent problems that are the result of a programming problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions: such as trying to access an object through a null reference; and indexing exceptions: such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity.

Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

The solution to rectify is to correct the programming logic where the exception has occurred or provide a check.


  4. What is checked exception?

Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.


  5. What is difference between Error and Exception?

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.)


  6. What is difference between ClassNotFoundException and NoClassDefFoundError?

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.


  7. How to create custom Exception?

To create you own exception extend the Exception class or any of its subclasses.

. class New1Exception extends Exception { } // this will create Checked Exception

. class NewException extends IOExcpetion { } // this will create Checked exception

. class NewException extends NullPonterExcpetion { } // this will create UnChecked exception


  8. When to make a custom checked Exception or custom unchecked Exception?

If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application do want to do anything to recover from the exception, make it an unchecked exception.

For e.g in client server model, if server is not able to talk with DB or some IO operation went wrong, its ok to throw the unchecked exception so that conatiner can handle it and throw appropriate error response.


  9. What is StackOverflowError?

The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory.

It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.


  10. Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?

Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them.

These exceptions are as much a part of that method's programming interface as its parameters and return value.


  11. Once the control switches to the catch block does it return back to the try block to execute the balance code?

No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).


  12. Where is the clean up code like release of resources is put in try-catch-finally block and why?

The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block.

Typically finally block contains release of connections, closing of result set etc.


  13. Is it valid to have a try block without catch or finally?

NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is acceptable to omit the either catch or the finally block but not both.


  14. How do you get the descriptive information about the Exception occurred during the program execution?

All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred.

It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.


  15. Why is not considered as a good practice to write a single catch all handler to catch all the exceptions?

You can write a single catch block to handle all the exceptions thrown during the program.

If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception occurred.

Also it will reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.


  16. What is exception matching?

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.


  17. Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of each other?

No. If the exceptions are siblings in the Exception class's hierarchy i.e. If one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.


  18. What happens if a method does not throw an checked Exception directly but calls a method that does? What does 'Ducking' the exception mean?

If a method does not throw an checked Exception directly but calls a method that throws an exception then the calling method must handle the throw exception or declare the exception in its throws clause.

If the calling method does not handle and declares the exception, the exceptions is passed to the next method in the method stack. This is called as ducking the exception down the method stack.


  19. Is an empty catch block legal?

Yes you can leave the catch block without writing any actual code to handle the exception caught.

e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the exception thrown.


  20. What is difference between Checked and Unchecked Exception in Java ?

This is another popular Java Exception interview question appears in almost all level of Java interviews.

The main difference between Checked and Unchecked Exception lies in there handling.

Checked Exception requires to be handled at compile time using try, catch and finally keywords or else compiler will flag error.This is not a requirement for Unchecked Exceptions.

Also all exceptions derived from java.lang.Exception classes are checked exception, exception those which extends RuntimeException, these are known as unchecked exception in Java.


  21. 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.


  22. 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.

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.


  23. What is difference between throw and throws keyword in Java?

One more Java Exception interview questions from beginners kitty. throw and throws keyword may look quite similar, especially if you are new to Java programming and haven't seen much of it.

Though they are similar in terms that both are used in Exception handling, they are different on how and where they are used in code. throws keyword is used in method signature to declare which checked exception method can throw, you can also declare unchecked exception, but that is not mandatory by compiler.

This signifies lot of things like method is not going to handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time exception handling etc.

On the other hand throw keyword is actually used to throw any Exception. Syntactically you can throw any Throwable (i.e. Throwable or any class derived from Throwable) , throw keyword transfers control of execution to caller so it can be used in place of return keyword.


  24. 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().


  25. What changes has been introduced in JDK7 related to Exception handling in Java ?

A relatively new and recent Exception interview question in Java.

JDK7 has introduced two major feature which is related to Error and Exception handling, one is ability to handle multiple exception in one catch block, popularly known as multi cache block and other is ARM blocks in Java 7 for automatic resource management, also known as try with resource.

Both of these feature can certainly help to reduce boiler plate code required for handling checked exceptions in Java and significantly improves readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I also recommend reading Java 7 Recipes book to get more insight on useful features introduced in Java 7, including these two.


  26. 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.


  27. 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 Java.


  28. What is difference in final, finalize and finally keyword in Java?

Another classic interview question in core Java, this was asked to one of my friend on his telephonic interview for core Java developer with Morgan Stanley.

final and finally are keyword, while finalize is method. final keyword is very useful for creating ad Immutable class in Java By making a class final, we prevent it from being extended, similarly by making a method final, we prevent it from being overridden,.

On the other hand, finalize() method is called by garbage collector, before that object is collected, but this is not guaranteed by Java specification.

finally keyword is the only one which is related to error and exception handling and you should always have finally block in production code for closing connection and resources.


  29. What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

1. throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.

2. throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it's caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

3. try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.

4. finally: finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurrs or not.


  30. Explain Java Exception Hierarchy?

Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects - Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

Errors are exceptional scenarios that are out of scope of application and it's not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error.

Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions.

Runtime Exceptions are caused by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.


  31. What are important methods of Java Exception Class?

Exception and all of it's subclasses doesn't provide any specific methods and all of the methods are defined in the base class Throwable.

1. String getMessage() - This method returns the message String of Throwable and the message can be provided while creating the exception through it's constructor.

2. String getLocalizedMessage() - This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.

3. synchronized Throwable getCause() - This method returns the cause of the exception or null id the cause is unknown.

4. String toString() - This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

5. void printStackTrace() - This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.


  32. What are different scenarios causing "Exception in thread main"?

Some of the common main thread exception scenarios are:-

1. Exception in thread main java.lang.UnsupportedClassVersionError:` This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.

2. Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.

3. Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn't have main method.

4. Exception in thread "main" java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.


  33. Provide some Java Exception Handling Best Practices?

Some of the best practices related to Java Exception Handling are:-

1. Use Specific Exceptions for ease of debugging.

2. Throw Exceptions Early (Fail-Fast) in the program.

3. Catch Exceptions late in the program, let the caller handle the exception.

4. Use Java 7 ARM feature to make sure resources are closed or use finally block to close them properly.

5. Always log exception messages for debugging purposes.

6. Use multi-catch block for cleaner close.

7. Use custom exceptions to throw single type of exception from your application API.

8. Follow naming convention, always end with Exception.

9. Document the Exceptions Thrown by a method using @throws in javadoc.

10. Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide null or empty response.


  34. How do you throw a Checked Exception from a Method?

The method addAmounts throws a new Exception. However, it gives us a compilation error because Exception is a Checked Exception.

All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception


  35. Why we need not to close file when we are using Try-with-resources in java?

Again experienced java developers must be well versed with this exception interview question. Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interface's close method automatically closes resources which are no longer needed) in java.

All the classes which implements AutoCloseable interface can be used inside Try-with-resources in java.


  36. What is exception propagation in java?

Experienced developers must know in detail about Exception handling interview question in java. Even freshers must try and understand this in depth concept of exception propagation in java.

Whenever methods are called stack is formed and an exception is first thrown from the top of the stack and if it is not caught, it starts coming down the stack to previous methods until it is not caught.

If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is terminated in java.


  37. Mention few exception handling best practices in java?

1. Throw exceptions when the method cannot handle the exception, and more importantly, must be handled by the caller.

In Servlets - doGet() and doPost() throw ServletException or IOException in certain circumstances where the request could not be read correctly. Neither of these methods are in a position to handle the exception, but the container is (which generally results in the 404 error page in most cases).

2. Bubble the exception if the method cannot handle it. This is a corollary of the above point, but applicable to methods that must catch the exception. If the caught exception cannot be handled correctly by the method, then it is preferable to bubble it.

3. Throw the exception right away. If an exception scenario is encountered, then it is a good practice to throw an exception indicating the original point of failure, instead of attempting to handle the failure via error codes, until a point deemed suitable for throwing the exception. In other words, attempt to minimize mixing exception handling with error handling.

4. Either log the exception or bubble it, but don't do both. Logging an exception often indicates that the exception stack has been completely unwound, indicating that no further bubbling of the exception has occurred. Hence, it is not recommended to do both at the same time, as it often leads to a frustrating experience in debugging.

5. Application should not try to catch Error - Because, in most of cases recovery from an Error is almost impossible. So, application must be allowed to terminate.


  38. Why it is always recommended that clean up operations like closing the DB resources to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not and raised exceptions are caught in the catch block or not.

By keeping the clean up operations in finally block, you will ensure that those operations will be always executed irrespective of whether exception is occurred or not.


  39. What are the rules we need to follow in overriding if super class method throws exception ?

1. If sub class throws checked exception super class should throw same or super class exception of this.

2. If super class method throws checked or unchecked exceptions its not mandatory to put throws in sub class overridden method.

3. If super class method throws exceptions in sub class if you want to mention throws then use same class or its sub class exception.


  40. What is try with resource block?

One more interesting feature of Java 7 is try with resource

In Java, if you use a resource like input or output streams or any database connection logic you always need to close it after using.

It also can throw exceptions so it has to be in a try block and catch block. The closing logic should be in finally block. This is a least the way until Java 7. This has several disadvantages:-

1. You'd have to check if your ressource is null before closing it

2. The closing itself can throw exceptions so your finally had to contain another try -catch

3. Programmers tend to forget to close their resources

PHP

PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more