Java Exception Handling Interview Questions

Java Exception Handling Interview Questions: Exception Handling is a crucial concept in Java programming that enables developers to handle errors and exceptions that may occur during the run-time of a Java program. Exception Handling Interview Questions in Java is integral to Java developer interviews. It assesses a candidate’s knowledge and expertise in handling exceptions, including their syntax, types, and best practices.

Exception Handling Interview Questions evaluate a candidate’s proficiency in implementing try-catch blocks, finally keywords, and throwing exceptions to handle runtime errors. In this context, this article presents some commonly asked Exception Handling Interview Questions in Java programming to help Java developers prepare for interviews and better understand Exception Handling in Java.

Exception Handling In Java Interview Questions

  • How to create a custom Exception?
  • What’s the difference between throws and throw keyword?
  • What’s the difference between checked and unchecked exception
  • What’s the parent class of the Exception class?
  • What’s the use of finally block?
  • Can we have a try block with finally block and without catch block?
  • How to handle the multiple exceptions?
  • Can we have more than one finally block?
  • Assume we have to try and finally block without a catch block. In that case, if an exception occurs in a try block, then how to handle it?
  • Assume we have two catch blocks, first catch block handling the “Exception” second catch block handling the “ArithmeticException”, in that case, if any arithmetic exception occurs in the try block, then which catch block will handle the exception?
  • Can we catch the error?
  • How to avoid NullPointerException?
  • Why are we using custom exceptions?
  • What is the difference between classnotfoundexception and noclassdeffounderror?
  • What is Exception Handling in Java?
  • In Java, what are the differences between a Checked and Unchecked?
  • What is the base class for Error and Exception classes in Java?
  • What is a finally block in Java?
  • What is the use of finally block in Java?
  • Can we create a finally block without creating a catch block?
  • Do we have to always put a catch block after a try block?
  • In what scenarios, a finally block will not be executed?
  • Can we re-throw an Exception in Java?
  • What is the difference between throw and throws in Java?
  • What is the concept of Exception Propagation?
  • When we override a method in a Child class, can we throw an additional Exception that is not thrown by the Parent class method?

Exception Handling Interview Questions

What are the different possible errors that we can encounter while compiling and executing the java program?
Answer: The different types of errors that we may encounter while compiling and executing a Java program are:

  • Compile-time error
  • Run-time errors
  • Logical errors

What is an Exception?
Answer: An exception is an event that disrupts the normal flow of instructions during the execution of a program. It is a runtime error in java. We can also say that the object-oriented representation of an abnormal event occurred during the program execution is known as “exception”. I.e., Exception is an object.

What are the problems if the exception is raised?
Answer:

  • If an exception is raised, JVM terminates the application abnormally.
  • If the program is terminated abnormally, the following problems may occur:
    – Users work and data loss.
    – The end-user is not informed properly about what went wrong.
    – Resources allocated to the application cannot be released gracefully.

What is exception handling?
Answer: It is a mechanism of dealing with exceptions and thereby preventing the dangerous effect caused by the exceptions.

How to handle exceptions in Java applications?
Answer:  There are two kinds of support from java to implement exception handling.

  • Language support and
  • API support
  • As far as language support concern, we have five keywords in java to implement exception handling:
try
catch
finally
throw
throws

To represent each abnormal scenario, there is a library exception class given in Java API.
Example: ArithmeticException, NullPointerExcpetion, NumberFormatException, ClassNotFoundException, FileNotFoundException etc.

What are the types of exceptions?
Answer: There are two types of exceptions in java

  • Checked exception
  • Un-checked exception

What are the checked exceptions?
Answer: Checked exceptions are those which the Java compiler forces you to catch. E.g., IOException.

What are runtime exceptions?
Answer:  Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic. The compiler does not check these at compile time.

What is the difference between error and an exception?
Answer:  An error is an irrecoverable condition occurring at runtime, such as OutOfMemory error. These are the JVM errors, and you cannot repair them at runtime. While exceptions are the conditions that occur because of bad input etc. For example:

  • FileNotFoundException will be thrown if the specified file does not exist.
  • 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 the user feedback for entering proper values, etc.)

How to create custom exceptions?
Answer:  Your class should extend class Exception or some more specific type thereof.

What should I do if I want an object of my class to be thrown as an exception object?
Answer: Extend the class from the Exception class. Or you can also extend your class from some more precise exception types.

What is the basic difference between the following approaches of exception handling?
Answer:

  • ‘try-catch’ block
  • Specifying the candidate exceptions in the throws clause

When should you use which approach?
Answer: In the first approach, you, is a program of the method, yourself are dealing with the exception. This is fine if you are in the best position to decide. If it is not the responsibility of the method to deal with its exceptions, then do not use this approach.

In the second approach, we are forcing the caller of the method to catch the exceptions that the method is likely to throw. This is often the approach library creator uses. They list the exception in the throws clause, and we must catch them. You will find the same approach throughout the java libraries we use.

Is it necessary that a catch block must follow each try block?
Answer: It is not necessary that a catch block must follow each try block. It should be followed by either a catch block or by a Finally block. And, whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

If I write return at the end of the try block, will the ‘finally’ block still execute?
Answer: Yes. Even if you write return as the last statement in the try block and no exception occurs, the ‘finally’ block will still execute and then returns the control.

If I write System.Exit (0); at the end of the try block, will the ‘finally’ block still execute?
Answer: No. In this case, the Finally block will not execute because when you say System.exit (0), the control immediately goes out of the program, and thus ‘finally’ block never executes.

What is the use of the ‘Finally’ block?
Answer: The “finally” statement identifies a block of code that cleans up regardless of whether an exception occurred within the try block or not. A “try” statement must be accompanied by at least one “catch” statement or a “finally” statement and may have multiple “catch” statements.

What is a user-defined exception in java?
Answer: User-defined exceptions are the exceptions defined by the application developer, which are errors related to a specific application. Application Developer can define the user-defined exception by inheriting the Exception class, as shown below. Using this class, we can throw new exceptions.

Java Example:

public class noFundException extends Exception
{
	//Statements
}
//Throw an exception using a throw statement:
public class Fund 
{ 
	public Object getFunds() throws noFundException
	{
		if (Empty()) throw new noFundException();
	}
}

User-defined exceptions should usually be checked.

By using one line of code, how can one prove that the array is not null but empty?
Answer: Print args.length. It will print 0. That means it is empty. But, if it is null, then it will be thrown a NullPointerException.

What is Checked and Unchecked Exception?
Answer: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked, forces the client programmers to deal with the possibility that the
exception will be thrown. Example: IOException has thrown by java.io.FileInputStream’s read() method· Unchecked exceptions are Runtime Exception and any of its subclasses.

Class Error and its subclasses also are unchecked. With an unchecked exception, the compiler doesn’t force client programmers either to catch the exception or declare it in a ‘throws’ clause. Client programs may not even know that the exception could be thrown.

Example: StringIndexOutOfBoundsException thrown by String’s charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

What are the checked exceptions?
Answer: Checked exceptions are those which the Java compiler forces you to catch. Example: IOException are checked exceptions.

If my class already extends from some other class, what should I do if I want an instance of my class to be thrown as an exception object?
Answer: You cannot do anything in this scenario. Java does not allow multiple inheritances and does not provide any exception interface too.

How does an exception permeate through the code?
Answer: An unhandled exception moves up the method stack in search of a matching. When an exception is thrown from a code that is wrapped in a ‘try’ block followed by one or more ‘catch’ blocks, a search is made for matching catch block. If a matching type is found, then that block will be invoked.

If a matching type is not found, then the exception moves up the method stack and reaches the caller method. The same procedure is repeated if the caller method is included in a ‘try-catch’ block. This process continues until a ‘catch’ block handling the appropriate type of exception is found. If it does not find such a block, then finally, the program terminates.

What are the different ways to handle exceptions?
Answer: There are two ways to handle exceptions:

  • By wrapping the desired code in a ‘try’ block followed by a ‘catch’ block to catch the exceptions. and
  • List the desired exceptions in the ‘throws’ clause of the method and let the caller of the method handle those exceptions.

How does a try statement determine which catch clause should be used to handle an exception?
Answer: When an exception is thrown within the body of a try statement, the catch clauses of the ‘try’ statement are examined in the order in which they appear. The first ‘catch’ clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

What is the catch or declare rule for method declarations?
Answer: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

What may a catch clause catch classes of exceptions?
Answer: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

Can an exception be re-thrown?
Answer: Yes, an exception can be re-thrown.

What class of exceptions are generated by the Java run-time system?
Answer: The Java runtime system generates Runtime Exception and Error exceptions.

What are the ‘final’, ‘finalize()’ and ‘finally’?
Answer: final: The ‘final’ keyword can be used for class, method, and variables. A final class cannot be subclassed and it prevents other programs from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.

Finalize (): The ‘finalize()’ method is used just before an object is destroyed and can be called just prior to garbage collection.

Finally: It is a keyword used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block executes. The ‘finally’ block will execute whether or not an exception is thrown.

For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception handling mechanism. This ‘finally’ keyword is designed to address this contingency.

Exception Handling Interview Questions For Experienced

What is an Exception in Java?
Ans: 
Exception: An event which disrupts the normal execution of a program is known as exception

What is an Exception handling in Java?
Ans: When such event occurs during execution of the program, in Java terms it is called an exception thrown or exception raised at runtime Which results in abrupt or abnormal termination of the program and rest of the program (code, i.e., after the line where exception is raised) won’t be executed To avoid abnormal termination of the program, all possible exceptions that could be thrown/raised needs to be handled This is known as exception handling in Java This helps to maintain graceful termination of the program

Java Exception Handling Interview Questions 1

Explain the exception hierarchy in Java? Whether multiple catches is possible for a single try block?
Ans: Throwable class is the root class for every exception, and it branches out to 2 main categories, i.e., Exception & Error

What is the difference between Exception v/s Error in Java?
Ans: Both are sub-class of Throwable class

  • The error is due to a lack of system resources, and it is non-recoverable. Therefore it isn’t feasible to handled by the programmer
  • The exception is due to programmatic logic, and it is recoverable. Therefore it must be handled using either try-catch block or throws clause

What is the superclass for Exception & Error in Java?
Ans: java.lang.Throwable is the root class for all types of Error & Exception

Read Also: Checked Exception VS Unchecked Exception In Java

What is the difference between checked exception v/s unchecked exceptions in Java?
Ans: 

Checked ExceptionUnchecked Exception
An exception which is checked at compile-time during compilation is known as Checked ExceptionAn exception which is NOT checked at compile-time is known as Unchecked Exception
Alternate definition: any line of code that could possibly throw an exception, and if raised during compilation is said to be checked exceptionAlternate definition: any line of code that could possibly throw an exception at runtime is said to be an unchecked exception
Except for Runtime exception & its child classes and error & its child classes, all other exceptions fall under the category of Checked ExceptionExample: Runtime exception & its child classes and error & its child classes
Some of the checked exception
IOException
SQLException
InterruptedException etc
Some of the unchecked exception
RuntimeException
NullPointerException
ArithmeticException etc

Explain important keywords in Java Exception handling?
Ans:
try, catch, finally, throw, throws

Try-Catch-Finally Blocks Combination

Is it valid to keep only try block without catch block or finally block?
Ans:
No, keeping try the block will raise the compile-time error stating “Syntax error, insert “Finally” to complete BlockStatements”
There are 3 possible combinations for the try block

  • the 1st try block is followed by catch block only
  • the 2nd try block is followed by finally block only
  • the 3rd combination is a sequence of a try-catch-finally block
Java Exception Handling Interview Questions 2

The only other possible combination is, try block followed by multiple catch blocks

Java Exception Handling Interview Questions 3

Whether multiple catches is possible for a single try block?
Ans:
Yes, it is very much possible to declare multiple catch blocks for a single try block. Example, as shown in the below screen capture

What are the rules for declaring multiple catch blocks?
Ans: 
For try with multiple catch blocks, an order of exception declaration is very important. That’s, a most specific exception must come up 1st in the order and follow by the more general exception.

In other words, if there exists a parent-child relationship between 2 exception then child exception must come 1st up in the order and then followed by parent exception Otherwise, compile-time error will be thrown stating “Exception Name-Of-Exception has already been caught” Also, declaring multiple catches with the same type of exception results in compile-time error stating “Unreachable catch block for Exception-Type. The catch block already handles it for Exception-Type.”

Java Exception Handling Interview Questions 4

Whether it is very mandatory to include curly braces for the try-catch-finally block, what happens if not included?
Ans: Yes, it is must include curly braces for try block, catch block, and finally block even if it contains just one line of code. Otherwise, the compile-time error will be thrown, as shown in the below screen capture.

Whether nested try-catch block is possible inside an outer try-catch block
Ans: Yes, nesting try-catch block inside another try-catch is possible & valid. It can be nested inside another try block, catch block or finally block

Java Exception Handling Interview Questions 5

Can we write any Java statements in between try block & catch block?
Ans: No, any statement in between try block & catch block results in the compile-time error. Example, as shown in the below screen capture

What is the main purpose of finally block in Java?
Ans: The main purpose of finally block is to perform clean-up activities or code clean-up like closing database connection & closing streams or file resources, etc. finally block is always associated with a try-catch block
Advantage: The beauty of finally block is that it is executed irrespective of whether an exception is thrown or NOT and it’s handled or NOT

Can we have finally block followed by try block (without catch block)?
Ans:
Yes, it is a valid sequence to have try block followed by finally block (without catch block or multiple blocks in between them)

Whether it is possible to write any statements after finally block?
Ans: If there is no return statement for a method, then it is valid to write any valid statements after finally block But if there is a method that returns a value then writing any statement after finally block results in compile-time error If there is a return statement after finally block, then it is valid

Whether finally block always executed, irrespective of any exception?
Ans: finally, block always executed irrespective of whether an exception is thrown or NOT, and it is handled or NOT But on one condition, finally won’t be executed when it encounters System.exit(); method as it kills the program execution further

Will finally block always be executed even if there is a return statement inside both try block or catch block?
Ans: Yes, finally block always executed even if there is a return statement inside the try-catch block

Explain various possible combinations to write return in a method enclosed with a try-catch-finally block?
Ans: 
There are 9 possible combinations to return a value from method enclosing the try-catch-finally block

Whether exception raises from a catch block?
Ans: It is very much possible that, the code inside the catch block to raises exception and this need to be handled Otherwise, the program terminates abnormally

Whether it is possible to declare catch block with the same exception-type twice, for example, ArithmeticException?
Ans: No, it isn’t possible to declare multiple catches with the same exception type. This leads to a compile-time error stating, “Unreachable catch block for ArithmeticException. The catch block already handles it for ArithmeticException”. Example, as shown in the below screen capture

  1. Java Exception Handling Interview Questions 6

Exception information:

What are the various methods available to print exception information in the console?
Ans: 
Whenever an exception is raised. then the respective method from where an exception is raised is responsible for creating an exception object with the following information like
1. Name of the exception
2. Description of the exception
3. Location at which exception is raised, i.e., the stack trace

  1. Method Description Format
    printStackTrace(); Prints all details related to an exception from exception object created by a method Name-of-ex : Description-of-exact location (StackTrace)
    toString(); Returns name & description of the exception in String format Name-of-ex : Description-of-ex
    getMessage(); Returns a detailed description of the exception thrown Description-of-ex
    getCause(); Returns the cause of the exception; Otherwise, returns null Caused By: class name & stack trace

Which method is used by default exception handler to print the stack trace?
Ans: 
printStackTrace(); method of Throwable class

Throw & throws keywords and Custom Exception

Explain throw keyword with its rules?
Ans: 
throw keyword:
User or programmers can also throw/raise exceptions explicitly at runtime on the basis of some business conditions. To raise such exception explicitly during program execution, we need to use throw keyword
Syntax: throw instanceOfThrowableType;
The main purpose of throw keyword is used to throw a user-defined exception or custom exception
Rules:
Both checked & unchecked exceptions can be thrown using throw keyword. The caller method has to handle the exception, whenever the target method declares exception using the throw keyword. Any valid Java statement after throw keyword is not reachable and it raises compile-time error Whenever thrown exception using throw keyword refers to a null reference, then instead of throwing the actual exception, NullPointerException will be thrown
Re-throwing: Caught exception in catch block can be re-thrown using throw keyword after some alteration

Explain throws keyword with its rules?
Ans: 
throws keyword:
Throws keyword is used to declare the exception that might raise during program execution. whenever exception might throw from program, the programmer doesn’t necessarily need to handle that exception using try-catch block instead simply declare that exception using throws clause next to method signature But this forces or tells the caller method to handle that exception; but again caller can handle that exception using try-catch block or re-declare that exception with throws clause, In other words, it can also be stated that, it provides information to the caller method that possible exception might raise during program execution and it needs to be handled

Rules: Whenever exception is declared using throws clause by target method, then caller method must handle this exception-type either try-catch block or declaring thrown exception-type using throws clause Any number of exceptions can be declared using throws clause, but they are all must be separated using commas (,) Constructor can also declare exception using throws clause User-defined exception or custom exception can also be declared using throws clause

Can we declare unchecked exceptions using throws keyword in the method signature?
Ans: Yes, it is possible to declare unchecked exception using throws clause

Java Exception Handling Interview Questions 7

What happens if there are some Java statements after explicit exception thrown using throw keyword?
Ans: the Compile-time error will be thrown stating “Unreachable code” Example, as shown in the below screen capture

Why is the only object of type Throwable (or its sub-type) allowed to throw?
Ans: Using the throw keyword, the only exception can be thrown. Therefore, all exception thrown should fall in the exception hierarchy (extending any one of the types of Throwable class). It can be checked or unchecked or a user-defined exception

Whether it is valid to throw Java object, which isn’t extending any Exception/Error from exception hierarchy?
Ans: As explained in the above question, the only exception can be thrown which should extend any one of the types of Throwable class Throwing normal Java object which isn’t extending any exception-type from exception hierarchy will result in a compile-time error stating “incompatible types”

Whether it is a normal termination or abnormal termination if we are using throws keyword?
Ans: It’s an abnormal termination, irrespective of whether program raises any exceptions or NOT, When we are using throws keyword to handle any exception raised during program execution, then it is always considered as an abnormal termination

Whether it is possible to create the custom exception, and can we throw this custom made exception?
Ans: Yes, it is very much possible to create a user-defined exception
Condition: while creating a user-defined exception, it should extend any one of the types of Throwable class. Otherwise, while throwing a user-defined exception, a compile-time error will be thrown, stating “incompatible types.”

Whether it is possible to throw a user-defined exception?
Ans: Yes, it is possible to throw a user-defined exception. The only condition is that it should extend any one of the types of Throwable class. Otherwise, while throwing a user-defined exception, a compile-time error will be thrown, stating “incompatible types.”

How to write a custom exception, explain its steps?
Ans: It is very simple, Write a Java class with any valid names adhering to Java syntax and extend any one of the types of Throwable class Later, this exception can be used with a throw, throws or catch keyword in exception handling

Explain Exception propagation?
Ans: Exception propagation: Whenever exception is raised from method and if it isn’t handled in the same method, then it is propagated back to the caller method This step is repeated until handler code is found in one of the caller methods in the runtime stack or else it reaches the bottom of the runtime stack This is known as Exception propagation

Rules for Exception propagation: By default, an unchecked exception is propagated back to the runtime stack one-by-one until it finds handler code or it reached the bottom of the stack Checked exception isn’t propagated, rather compiler forces the programmer to handle checked exception in the same method by surrounding with try-catch block or declaring with throws keyword

Explain re-throwing an exception?
Ans: It is possible & valid to the re-throw caught an exception in the catch block. It is generally used in a few cases, When a method catches the exception and doesn’t want to handle, instead it wants to propagate the exception to the caller method (basically delegating the responsibly to caller method) Sometimes, method catches one type of exception and convert to another exception and then throw It is also used to add some user message to the caught exception before re-throwing to the caller method

Note: in all cases, it the responsibility of the caller method to handle this exception whether by surrounding with try-catch or declare the throws clause

Difference between throw and throws keywords?
Ans:

throw clause/keywordthrows clause/keyword
the throw keyword is used to throw an exception explicitlythrows keyword is used to declare an exception to delegate/indicate exception handling the responsibility to caller method
the throw keyword is always followed by an instance of the Throwable type or exception typethrows keyword is always followed by an exception list (with the comma separating them)
the throw keyword is used within the method, i.e., to throw an exception from try-catch block enclosed within the methodthrows keyword is used next to the method signature
Syntax: throw instanceOfExceptionType;Syntax: access_modifier return_type method_name() throws exception_list;
Maximum of only one exception can be thrown using throw keywordThrown exception can be checked exception or unchecked exception or a user-defined exceptionAny number of the exception can be thrown using throws keyword, but they are all separated by a comma (,)

Difference between try-catch block v/s throws keyword?

try-catch blockthrows keyword
Using try-catch block, we can handle exception surrounding the code that might raise an exceptionWhereas using throws keyword, we can declare the exception that might arise from that method
Caught exception in the catch block can be re-thrown after some alterationThere is no such flexibility, as it directly throws an exception
the try-catch block ensures graceful termination for that particular method (except one scenario when-catch block throws an exceptionIt doesn’t guarantee graceful termination. In most cases, throws declaration leads to abnormal termination

Explain the difference between the final v/s finally v/s finalize()?
Ans:

  • Final is a keyword used for restricting further alteration in inheritance
  • Finally is associated with try-catch in exception handling for clean-up activity
  • Finalize() is a method associated with the garbage collector to a de-allocate resource associated with Object

Explain the difference between ClassNotFoundException v/s NoClassDefFoundError in detail ?

ClassNotFoundExceptionNoClassDefFoundError
This generally occurs, when required .class is missing when the program encounters class load statement such as,
Class.forName(“class.name”);
ClassLoader.loadClass(“class.name”);
ClassLoader.findSystemClass(“class.name”);Reason: a required file missing in the classpath due to the execution of the program without updating JAR file at runtime
This is very much similar, but the difference is required .class file is available during compile-time & missing at runtime possible

 

Reason: It is deleted after compilation, or there could be a version mismatch

The fully qualified class name is java.lang.ClassNotFoundExceptionA fully qualified class name is java.lang.NoClassDefFoundError
It falls under the category of Exception, i.e., a direct subclass of java.lang.ExceptionIt falls under the category of Error, i.e., sub-class of java.lang.Error through java.lang.LinkageError
It is a checked exception. Therefore it needs to be handled, whenever class loading is encountered as stated in point no.1All errors come under the unchecked exception category. Therefore NoClassDefFoundError is also an unchecked exception
As it is checked exception, a programmer can provide handling code either using the try-catch block or can declare throws clauseTherefore, and it is recoverableThe Java Runtime system throws errors during program execution. Therefore, it is non-recoverable

Java 1.7 Version Features

Explain, what are the new features introduced in Java 1.7 version?
Ans: 
New featured introduced in Java 1.7 version are, try-with-resources for automatic resource management multi-catch block for different grouping exception-type for similar handler code with pipe character separating them

Explain the Automatic Resource management feature in Java exception handling?
Ans: 
try-with-resources statement:
Using try-with-resources statement, the programmer doesn’t need to close the opened resources explicitly Rather it will be automatically closed once control reaches the end of try-catch block This new feature introduced in Java 1.7 version is alternatively referred as Automatic Resource Management e.; ARM

Rules: All resources declared as part of the try-with-resources statement must be AutoCloseable (i.e., all resources must implement the java.lang.AutoCloseable interface)

Multiple resources can be declared inside try block argument, but they are all must be separated by the semi-colon (;)
While using the try-with-resources statement, try block itself is enough. There is no compulsion to write either catch block or finally block following the try block, whereas in prior versions try either catch block must follow block or finally block

All resource reference variable declared inside the try block argument is implicitly final. Therefore, the resource reference variable can’t change or re-assigned within the try block

Whether it is mandatory to follow catch block or finally block after the try-with-resources statement (try block)?
Ans: 
It isn’t mandatory to have either catch block or finally block following try block alone can work without the need of catch block or finally block

  1. Java Exception Handling Interview Questions 8

How is a multi-catch block is useful over traditional multiple catch blocks?
Ans: 
Multi-catch block: In Java 1.6 or lesser version, whenever multiple exceptions are thrown, then programmer has to provide multiple catch block to catch different types of exception, although exception handling code is the same But in Java 1.7 version, we can write/code single catch block to handle multiple types of exceptions using multi-catch block By using multi-catch block, helps to provide same handler code by grouping different exception-types. And program/code becomes more readable with lesser lines of code

Rules: There shouldn’t be any relationship between the declared exception-type in a multi-catch block. Otherwise, compile-time error will be thrown stating “The exception <child-exception-type> is already caught by the alternative <parent-exception-type>” If a catch block handles more than one exception-type (i.e., multi-catch block), then exception variable is implicitly final Any changes or re-assignment to this implicit final variable within catch block results in compile-time error

Java Exception Interview Questions

Explain the rules for exception handling with respect to method overriding?
Ans: 
Below listed are the rules for exception handling when overriding,

Rule 1: If parent class method doesn’t declare any exception, Then child class overriding method can declare any type of unchecked exception (this is the only possibility) If a child class overriding method declares checked exception, the compiler throws a compile-time error stating “Exception IOException is not compatible with throws clause in ParentClass.testMethod()” Then child class overriding method can declare no exception to the overriding method of child class (very much same as that of the overridden method in parent class –> exactly same method signature)

Rule 2: If parent class method declares unchecked exception, Then child class overriding method can declare any type of unchecked exception (not necessarily the same exception as that of parent class method) If child class overriding method declares any checked exception, then compiler throws compile-time error stating “Exception IOException is not compatible with throws clause in ParentClass.testMethod()” Then child class overriding method can declare no exception to the overriding method of the child class

Rule 3: If parent class method declares checked exception, Then child class overriding method can declare any type of unchecked exception Then child class overriding method can declare the same type of checked exception or one of its sub-class or no exception Then child class overriding method can declare no exception in the overriding method of the child class

Rule 4: If parent class method declares both checked & unchecked exceptions, Then child class overriding method can declare any type of unchecked exception Then child class overriding method can declare the same type of checked exception or one of its sub-class or no exception Then child class overriding method can declare no exception in the overriding method of child class

What is an unreachable block in Java?
Ans: 
There are various scenarios when this compile-time error is encountered If there is any statement after throw clause When declaring multiple catch blocks, parent exception declared before than child exception Declaring catch block for checked exception-type, when actually try never going to throw that exception Any valid Java statements after return statement Any valid Java statement after finally block, if finally block is returning some value
Note: try examples on your own

Can a method return an exception?
Ans: 
A method can only throw exception Method can’t return an exception.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment