Top 19 Java Exception Handling Interview Questions
Q1. What Is Try-with-sources Or Arm In Java 7?
Java 7 added a brand new form of try called attempt-with-assets for Automatic Resource Management (ARM). Here resource is an object that ought to be closed after the program is finished with it. Example of assets might be an opened document deal with or database connection and so on.
Before the advent of try-with-assets we needed to explicitly close the assets once the attempt block completes normally or all of sudden.
Try
br = new BufferedReader(new FileReader("C:check.Txt"));
System.Out.Println(br.ReadLine());
trap (IOException e)
e.PrintStackTrace();
ultimately
strive
if (br != null)
System.Out.Println("Closing the file");
br.Near();
capture (IOException ex)
ex.PrintStackTrace();
strive-with-assets helps in reducing such boiler plate code. Let's see the same example the use of attempt-with-resources.
Attempt(BufferedReader br = new BufferedReader(new FileReader("C:take a look at.Txt")))
System.Out.Println(br.ReadLine());
seize (IOException e)
e.PrintStackTrace();
Q2. Final Vs Finally Vs Finalize?
Final - very last keyword is used to restriction in a few manner. It may be used with variables, strategies and lessons. When a variable is said as final, its fee cannot be modified once it's miles initialized. Except in case of blank very last variable, which need to be initialized in the constructor.
If you make a technique final in Java, that method can not be overridden in a sub elegance.
If a class is asserted as final then it can not be sub classed.
Sooner or later - subsequently is part of exception managing mechanism in Java. In the end block is used with strive-trap block. Finally block is usually completed whether any exception is thrown or no longer and raised exception is handled in seize block or now not. Since in the end block constantly executes accordingly it's miles in the main used to close the opened sources like database connection, record handles and many others.
Finalize() - finalize() technique is a covered approach of java.Lang.Object magnificence. Since it's miles in Object class therefore it is inherited through every magnificence. This approach is known as with the aid of garbage collector thread earlier than getting rid of an item from the memory. This method can be overridden by way of a class to provide any cleanup operation and offers item final hazard to cleanup before getting garbage accumulated.
Included void finalize() throws Throwable
//aid clean up operations
Q3. What Is Throw Keyword?
It is feasible for a Java program to throw an exception explicitly this is completed the use of the throw assertion.
The popular form of throw is -
throw throwableObject;
We can get this throwableObject in 2 approaches -
By the usage of the Exception parameter of capture block.
Create a brand new one using the new operator.
Strive
throw new NullPointerException();
catch(NullPointerException nExp)
System.Out.Println("Exception caught in capture block of displayValue");
throw nExp;
Q4. What Is Finally Block?
When an exception happens in the code, the flow of the execution may also trade or maybe quit all of sudden. That might also reason trouble if a few sources have been opened within the method.
As exp if a record was opened in a method and it become no longer closed ultimately as some exception came about then the resources might also remain open consuming reminiscence. Eventually presents that exception-managing mechanism to clean up.
Code with within the ultimately block may be accomplished after a attempt/capture block has completed. The in the end block can be executed whether or not or not an exception is thrown.
Q5. Explain The Exception Hierarchy In Java?
Throwable class is the tremendous class of all the exception sorts. Below Throwable class there are subclasses which denotes two wonderful branches of exceptions -
Exception - An Exception indicates that a trouble has passed off, however it isn't a severe machine hassle. The user packages you write will throw and catch Exceptions.
Error - It defines exceptions that aren't predicted to be stuck via your application. Exceptions of type Error are used by the Java run-time device to suggest errors having to do with the run-time environment, itself.
Examples of mistakes are StackOverflowError, OutOfMemoryError and so forth.
Below Exception there is a awesome subclass RunTimeExcpetion - RunTimeExcpetion and its descendants denote the splendid conditions which can be external to the application, and the application commonly cannot anticipate or get over them.
Q6. What Is The Error In The Following Code?
@class Parent
@ public void displayMsg() throws IOException
2@ System.Out.Println("In Parent displayMsg()");
2@ throw new IOException("Problem in technique - displayMsg - Parent");
2@
2@
2@public elegance ExceptionOverrideDemo extends Parent
2@ public void displayMsg() throws Exception
2@ System.Out.Println("In ExceptionOverrideDemo displayMsg()");
2@ throw new Exception("Problem in technique - displayMsg - ExceptionOverrideDemo");
2@
2@
Here figure class had declared IOException where as subclass has declared Exception. Exception is the notable magnificence of IOException therefore it is incorrect in keeping with the policies of method overriding and exception coping with. Thus the code will deliver compiler errors.
Q7. Is It Necessary That Each Try Block Must Be Followed By A Catch Block?
No it isn't always mandatory that there ought to be a seize block after a strive block. Strive block can have handiest an identical finally block. So there are those legitimate combnations attempt-trap-ultimately, try-catch, try-finally.
Q8. What Is Multi-catch Statement In Java 7?
Before Java 7 multi-seize announcement, if or more exceptions have been dealt with within the identical manner, we nonetheless had to write separate trap blocks for handling them.
Seize(IOException exp)
logger.Mistakes(exp);
throw exp;
capture(SQLException exp)
logger.Mistakes(exp);
throw exp;
With Java 7 and later it's far feasible to trap more than one exceptions in a single catch block, which eliminates the duplicated code. Each exception type inside the multi-seize assertion is separated by way of Pipe image (catch SQLException exp)
logger.Blunders(exp);
throw exp;
Q9. What Is Throws Clause?
If in a method we do not need to deal with any exception however need to go away it to the calling approach to deal with any exception that is thrown by way of the known as approach, it's miles achieved the use of throws key-word.
Using throws a technique can simply claim the exception it is able to throw and callers of the method have to offer exception managing for the ones exceptions (or they also can claim them the usage of throws).
General shape of a method declaration that consists of a throws clause
kind method-name(parameter-listing) throws exception-listing
// frame of method
Q10. What Is Exception Propagation?
When an brilliant condition occurs inside a technique, the technique (in which the exception occurred) creates an Exception Object and throws it. The created exception object incorporates records approximately the mistake, its kind and the kingdom of this system whilst the mistake occurred.
The approach wherein the exception is thrown may manage that exception itself or bypass it on. In case it passes it on, run time machine goes thru the method hierarchy that have been called to get to the present day method to search for a technique that can handle the exception.
If your application is not able to seize any precise exception, on the way to ultimately be processed by the default handler. This technique of going thru the technique stack is known as Exception propagation.
Q11. What Is Exception Handling?
Exception Handling in Java presents a way to address a scenario when an exception is thrown and suggests a significant message to the user and hold with the float of the program.
When an incredible situation occurs with in a technique, the technique (where the exception came about) creates an Exception Object and throws it. The created exception object carries statistics about the mistake, its kind and the nation of the program when the error happened.
The approach in which the exception is thrown may additionally manage that exception itself or pass it on. In case it passes it on, run time device goes thru the method hierarchy that had been known as to get to the modern-day method to look for a technique which could take care of the exception.
Five keywords used to manage Java exception managing
strive - Any code that would throw an exception is enclosed within a strive block.
Catch - If an exception occurs in strive block, trap block can provide exception handlers to deal with it in a rational way.
Ultimately - The sooner or later block constantly executes while the attempt block exits. So, any code that need to execute after a try block is finished need to be installed ultimately block.
Throw - throw is used to manually thrown an exception.
Throws - Any exception that is thrown in a method however now not dealt with there ought to be specified in a throws clause.
Q12. What Are Multiple Catch Blocks?
There is probably a case when a code enclosed with in a strive block throws more than one exception. To deal with those kinds of conditions, two or more seize clauses may be designated in which each seize clause catches a one of a kind kind of exception. When an exception is thrown, each of the trap statement is inspected so as, and the primary one whose type matches that of the thrown exception is accomplished.
Int a[] = zero;
strive
int b = 7/a[i];
catch(ArithmeticException aExp)
aExp.PrintStackTrace();
capture(ArrayIndexOutOfBoundsException aiExp)
aiExp.PrintStackTrace();
Q13. Is It Possible To Have A Finally Block Without Catch?
Yes we are able to have a attempt-finally block, seize is optionally available. We could have these combos attempt-capture-sooner or later, strive-seize, try-subsequently.
Q14. What Are The Rules Of Exception Handling With Respect To Method Overriding?
There are positive restrictions at the same time as overriding a method in case of exception handling in Java. Broadly there are two policies -
If superclass method has not declared any exception the usage of throws clause then subclass overridden approach can not claim any checked exception even though it could claim unchecked exception.
If superclass method has declared an exception the usage of throws clause then subclass overridden approach can do one of the three things.
Sub-magnificence can declare the identical exception as declared in the amazing-magnificence method.
Subclass can claim the subtype exception of the exception declared within the superclass approach. But subclass method cannot declare any exception this is up inside the hierarchy than the exception declared within the amazing class technique.
Subclass approach can choose not to claim any exception at all.
Q15. What Is A Nested Try Statement?
A attempt-trap-ultimately block can are living inner another strive-trap-ultimately block this is referred to as nested try declaration.
Public class NestedTryDemo
public static void essential(String[] args)
strive
System.Out.Println("In Outer try block");
try
System.Out.Println("In Inner strive block");
int a = 7 / zero;
trap (IllegalArgumentException e)
System.Out.Println("IllegalArgumentException stuck");
ultimately
System.Out.Println("In Inner ultimately");
catch (ArithmeticException e)
System.Out.Println("ArithmeticException caught");
in the end
System.Out.Println("In Outer subsequently");
Q16. What Is The Difference Between Checked Exception And Unchecked Exception?
Checked Exception is a right away subclass of Exception wherein as unchecked exception is a subclass of RunTimeException.
Checked exception ought to be wrapped in a try-trap block or certain as throws clause in which as there's no such requirement for unchecked exception.
Failure to offer exception coping with mechanism for checked exception bring about compiler blunders whereas no assemble time error for unchecked exception.
Checked exceptions are designed to lessen the number of exceptions which are not properly dealt with and wherein there's an inexpensive chance for recovery. UnCheckedExceptions are by and large programming errors.
Q17. Difference Between Throw And Throws?
Throw is used to throw an exception.
Throws is used to claim an exception, in the approach signature, that can be thrown from a technique.
Q18. What Is The Difference Between Error And Exception?
Exception - An Exception indicates that a hassle has occurred, but it isn't a extreme system problem. The person packages you write will throw and trap Exceptions.
Error - It defines exceptions that are not predicted to be caught through your program. Exceptions of kind Error are used by the Java run-time machine to suggest errors having to do with the run-time environment, itself.
Examples of error are StackOverflowError, OutOfMemoryError and many others.
Q19. When Is Custom Exception Class Needed? How To Create A Custom Exception Class?
According to Java Docs, you need to write your personal exception training in case you wer yes to any of the following questions; otherwise, you may probable use someone else's.
Do you want an exception kind that isn't represented by those within the Java platform?
Would it assist users if they might differentiate your exceptions from those thrown by means of lessons written via different vendors?
Does your code throw more than one associated exception?
F you operate a person else's exceptions, will users have get admission to to those exceptions? A comparable question is, ought to your package be impartial and self-contained?
