Exception Handling Interview Questions and Answers
Q1. What is an exception Handling?
Ans: Exception managing is the process of responding to the prevalence, during computation, of exceptions – anomalous or extraordinary conditions requiring special processing – regularly converting the normal go with the flow of software execution.
An exception is an extraordinary occasion that takes place during the execution of a application and disrupts go with the flow of the program’s commands.
Q2. What are some blessings of exceptions?
Ans: Traditional error detection and dealing with techniques often lead to spaghetti code tough to keep and hard to study. However, exceptions allow us to separate the center good judgment of our utility from the information of what to do while something unexpected happens.
Also, for the reason that JVM searches backward via the decision stack to locate any strategies inquisitive about coping with a particular exception; we benefit the capacity to propagate an error up inside the name stack with out writing additional code.
Also, because all exceptions thrown in a software are items, they may be grouped or labeled primarily based on its elegance hierarchy. This lets in us to trap a set exceptions in a unmarried exception handler by specifying the exception’s superclass inside the trap block.
Q3. What are the Exception Handling Keywords in Java?
Ans: There are four keywords used in java exception handling.
Throw: Sometimes we explicitly need to create exception object and then throw it to halt the ordinary processing of this system. Throw keyword is used to throw exception to the runtime to address it.
Throws: When we're throwing any checked exception in a technique and not coping with it, then we need to apply throws keyword in technique signature to permit caller program know the exceptions that might be thrown with the aid of the technique. The caller approach may deal with these exceptions or propagate it to it’s caller method using throws keyword. We can offer a couple of exceptions in the throws clause and it may be used with most important() technique also.
Attempt-capture: We use strive-catch block for exception coping with in our code. Try is the start of the block and trap is on the quit of try block to handle the exceptions. We will have multiple capture blocks with a attempt to strive-capture block may be nested also. Seize block calls for a parameter that ought to be of kind Exception.
Finally: eventually block is non-compulsory and can be used simplest with try-catch block. Since exception halts the manner of execution, we would have a few resources open a good way to now not get closed, so we will use in the end block. Sooner or later block gets done constantly, whether or not exception occurrs or not.
Q4. What is the distinction among a checked and an unchecked exception?
Ans: A checked exception have to be dealt with within a try-capture block or declared in a throws clause; while an unchecked exception isn't required to be handled nor declared.
Checked and unchecked exceptions are also called bring together-time and runtime exceptions respectively.
All exceptions are checked exceptions, besides those indicated with the aid of Error, RuntimeException, and their subclasses.
Q5. What is the cause of the throw and throwskeywords?
Ans: The throws key-word is used to specify that a way may additionally increase an exception during its execution. It enforces express exception managing when calling a way:
public void simpleMethod() throws Exception
The throw key-word allows us to throw an exception object to interrupt the normal go with the flow of this system. This is most typically used whilst a program fails to fulfill a given situation:
throw new TooComplicatedException( "The mission is simply too complex" );
Q6. What is the distinction between an exception and error?
Ans: An exception is an event that represents a circumstance from that is possible to recover, while mistakes represents an external scenario normally not possible to get over.
All mistakes thrown through the JVM are times of Error or one among its subclasses, the more common ones encompass however aren't restricted to:
OutOfMemoryError: Thrown while the JVM can not allocate greater gadgets due to the fact it is out memory, and the rubbish collector became not able to make greater available.
StackOverflowError: Occurs whilst the stack area for a thread has run out, generally due to the fact an utility recurses too deeply.
ExceptionInInitializerError: alerts that an unexpected exception befell throughout the assessment of a static initializer.
NoClassDefFoundError: is thrown when the classloader attempts to load the definition of a category and couldn’t locate it, normally because the desired classfiles had been not observed inside the classpath.
UnsupportedClassVersionError: happens when the JVM tries to read a class record and determines that the model inside the document isn't always supported, generally because the file was generated with a more moderen version of Java.
Although an error can be treated with a try announcement, this is not a advocated practice due to the fact there's no assure that the program can be able to do whatever reliably after the mistake became thrown.
Q7. What are critical methods of Java Exception Class?
Ans: Exception and all of it’s subclasses doesn’t offer any unique strategies and all of the strategies are described inside the base magnificence Throwable:
String getMessage(): This method returns the message String of Throwable and the message can be furnished even as creating the exception through it’s constructor.
String getLocalizedMessage(): This approach is furnished so that subclasses can override it to provide locale precise message to the calling software. Throwable magnificence implementation of this approach actually use getMessage() method to return the exception message.
Synchronized Throwable getCause(): This approach returns the purpose of the exception or null identity the reason is unknown.
String toString(): This method returns the information about Throwable in String layout, the lower back String carries the name of Throwable magnificence and localized message.
Void printStackTrace(): This method prints the stack trace information to the standard error move, this approach is overloaded and we will bypass PrintStream or PrintWriter as argument to write down the stack trace information to the report or move.
Q8. What is exception chaining?
Ans: Occurs whilst an exception is thrown in reaction to any other exception. This permits us to find out the whole records of our raised hassle:
trap (FileNotFoundException ex)
throw new TaskException( "Could now not perform undertaking" , ex);
Q9. How can you cope with an exception?
Ans: By using a strive-capture-sooner or later announcement:
Capture (ExceptionType1 ex)
Trap (ExceptionType2 ex)
Sooner or later
The block of code in which an exception may also occur is enclosed in a try block. This block is likewise referred to as “protected” or “guarded” code.
If an exception happens, the trap block that suits the exception being thrown is accomplished, if now not, all trap blocks are neglected.
The finally block is continually finished after the strive block exits, whether an exception turned into thrown or now not inner it.
Q10. What is a stacktrace and the way does it relate to an exception?
Ans: A stack hint presents the names of the training and strategies that were known as, from the start of the application to the factor an exception passed off.
It’s a totally beneficial debugging tool because it enables us to determine precisely in which the exception was thrown in the application and the authentic reasons that brought about it.
Q11. What is difference among very last, sooner or later and finalize in Java?
Ans: Final and ultimately are key phrases in java whereas finalize is a technique.
Final keyword may be used with magnificence variables so that they can’t be reassigned, with class to keep away from extending with the aid of lessons and with techniques to keep away from overriding with the aid of subclasses, eventually key-word is used with try-capture block to offer statements so as to continually receives performed even if some exception arises, normally finally is used to close sources. Finalize() approach is accomplished by way of Garbage Collector earlier than the item is destroyed, it’s amazing manner to make sure all the worldwide sources are closed.
Q12. What happens when exception is thrown by means of most important method?
Ans: When exception is thrown by means of important() technique, Java Runtime terminates this system and print the exception message and stack hint in gadget console.
Q13. Can we've an empty catch block?
Ans: We can have an empty seize block however it’s the example of worst programming. We have to never have empty seize block due to the fact if the exception is stuck by using that block, we can don't have any records about the exception and it wil be a nightmare to debug it. There should be as a minimum a logging declaration to log the exception info in console or log files.
Q14. What is OutOfMemoryError in Java?
Ans: OutOfMemoryError in Java is a subclass of java.Lang.VirtualMachineError and it’s thrown by using JVM when it ran out of heap memory. We can restore this mistake via supplying extra reminiscence to run the java application thru java alternatives.
Q15. Explain Java 7 ARM Feature and multi-catch block?
Ans: If you're catching a lot of exceptions in a unmarried strive block, you will notice that seize block code seems very unsightly and primarily consists of redundant code to log the error, retaining this in mind Java 7 one of the function become multi-trap block wherein we can capture multiple exceptions in a single seize block. The trap block with this selection looks like below:
seize Exception ex)
throw new MyException(ex.GetMessage());
Most of the time, we use eventually block just to close the assets and once in a while we neglect to shut them and get runtime exceptions while the sources are exhausted. These exceptions are tough to debug and we'd want to look at every place wherein we are the use of that kind of aid to make certain we are remaining it. So java 7 one of the improvement become strive-with-sources in which we can create a aid within the strive announcement itself and use it inside the strive-seize block. When the execution comes out of strive-capture block, runtime environment robotically close those resources. Sample of attempt-capture block with this development is:
attempt (MyResource mr = new MyResource())
System.Out.Println("MyResource created in try-with-assets");
seize (Exception e)
Q16. What are specific scenarios inflicting “Exception in thread fundamental”?
Ans: Some of the common fundamental thread exception situations are:
Exception in thread essential java.Lang.UnsupportedClassVersionError: This exception comes while your java class is compiled from every other JDK version and you are attempting to run it from another java model.
Exception in thread most important java.Lang.NoClassDefFoundError: There are two variations of this exception. The first one is where you provide the magnificence full call with .Magnificence extension. The second situation is when Class isn't always discovered.
Exception in thread foremost java.Lang.NoSuchMethodError: main: This exception comes whilst you are attempting to run a category that doesn’t have main approach.
Exception in thread “major” java.Lang.ArithmeticException: Whenever any exception is thrown from major technique, it prints the exception is console. The first component explains that exception is thrown from primary technique, 2nd component prints the exception class name after which after a colon, it prints the exception message.
Q17. What exception could be thrown executing the following code block?
Ans: Integer ints = 1, 2, 3 , null , 7, eight, nine ;
System.Out.Println( "fee = " + ints[ 1 ][ 1 ].IntValue());
It throws an ArrayIndexOutOfBoundsException because we’re looking to get admission to a function extra than the length of the array.
Q18. Will the subsequent code bring together?
Throw new RuntimeException( new Exception( "Chained Exception" ));
Yes. When chaining exceptions, the compiler handiest cares about the first one within the chain and, because it detects an unchecked exception, we don’t want to add a throws clause.
Q19. Is there any manner of throwing a checked exception from a method that doesn't have a throws clause?
Ans: Yes. We can take advantage of the kind erasure finished with the aid of the compiler and make it suppose we're throwing an unchecked exception, when, in reality; we’re throwing a checked exception:
public <T extends Throwable> T sneakyThrow(Throwable ex) throws T
throw (T) ex;
public void methodWithoutThrows()
this .<RuntimeException>sneakyThrow( new Exception( "Checked Exception" ));
Q20. Provide some Java Exception Handling Best Practices?
Ans: Some of the quality practices related to Java Exception Handling are:
Use Specific Exceptions for ease of debugging.
Throw Exceptions Early (Fail-Fast) inside the program.
Catch Exceptions late inside the software, allow the caller manage the exception.
Use Java 7 ARM feature to ensure assets are closed or use sooner or later block to close them nicely.
Always log exception messages for debugging functions.
Use multi-capture block for purifier near.
Use custom exceptions to throw single sort of exception out of your application API.
Follow naming convention, usually quit with Exception.
Document the Exceptions Thrown with the aid of a method the usage of @throws in javadoc.
Exceptions are pricey, so throw it handiest when it makes experience. Else you could trap them and offer null or empty reaction.