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 keywords?
- What’s the difference between checked and unchecked exception
- What’s the parent class of the Exception class?
- What’s the use of the finally block?
- Can we have a try block with a finally block and without a 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, how should we handle it?
- Assume we have two catch blocks: the first catch block handling the “Exception” and the 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 that occurred during the program execution is known as an “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 for dealing with exceptions and thereby preventing their dangerous effects.
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 concerned, 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 that the Java compiler forces you to catch. E.g., IOException.
What are runtime exceptions?
Answer: Runtime exceptions are exceptions thrown at runtime because of either wrong input data or wrong business logic. The compiler does not check these at compile time.
What is the difference between an error and an exception?
Answer: An error is an irrecoverable condition occurring at runtime, such as an 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.
- If you try using a null reference, a NullPointerException will occur. In most 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: You can extend the class from the Exception class or 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 are a program of the method; you 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 force the method’s caller to catch the exceptions that the method is likely to throw. This is often the approach the library creator uses. They list the exceptions 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: A catch block does not need to follow each try block. It should be followed by either a catch block or a finally block. Whatever exceptions are likely to be thrown should be declared in the method’s throws clause.
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 return 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 leaves the program, and thus, the ‘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 errors related to a specific application defined by the application developer. The Application Developer can define a 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 a 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 been thrown by java.io.FileInputStream’s read() method· Unchecked exceptions are Runtime Exception and any of its subclasses.
Class Error and its subclasses are also unchecked. With an unchecked exception, the compiler doesn’t force client programmers to catch it 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 that the Java compiler forces you to catch. For example, IOExceptions 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, either.
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 code wrapped in a ‘try’ block followed by one or more ‘catch’ blocks, a search is made for a 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 a method’s body, the method must either catch it 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, including 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 Exception.
What are the ‘final’, ‘finalize()’ and ‘finally’?
Answer: final: The ‘final’ keyword can be used for classes, methods, 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, and 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 that creates a block of code that will be executed after a try/catch block has been 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, you will not want the exception-handling mechanism to bypass the code that closes the file. 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 that disrupts the normal execution of a program is known as an 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 an exception is raised) won’t be executed To avoid abnormal termination of the program, all possible exceptions that could be thrown/raised need to be handled This is known as exception handling in Java This helps to maintain graceful termination of the program
Explain the exception hierarchy in Java. Are multiple catches possible for a single try block?
Ans: The 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 the Throwable class
- The error is due to a lack of system resources, and it is non-recoverable. Therefore it isn’t feasible to handle the programmer
- The exception is due to programmatic logic, and it is recoverable. Therefore it must be handled using either a try-catch block or a 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
What is the difference between checked exceptions v/s unchecked exceptions in Java?
Ans:
Checked Exception | Unchecked Exception |
An exception which is checked at compile-time during compilation is known as Checked Exception | An 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 exception | Alternate 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 Exception | Example: 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 the try block without the 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 a 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
The only other possible combination is, try a block followed by multiple catch blocks
Are multiple catches possible for a single try block?
Ans:
Yes, it is very much possible to declare multiple catch blocks for a single try block. For example, as shown in the below screen capture
What are the rules for declaring multiple catch blocks?
Ans: For a try with multiple catch blocks, the order of exception declaration is very important. That is, the most specific exception must appear first, followed by the more general exception.
In other words, if there exists a parent-child relationship between 2 exceptions then the child exception must come 1st up in the order and then be followed by the parent exception Otherwise, a 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 a compile-time error stating “Unreachable catch block for Exception-Type. The catch block already handles it for Exception-Type.”
Whether it is very mandatory to include curly braces for the try-catch-finally block, what happens if not included?
Ans: Yes, it must include curly braces for the try, catch, and finally blocks, even if they contain just one line of code. Otherwise, a compile-time error will be thrown, as shown in the screenshot below.
Whether a nested try-catch block is possible inside an outer try-catch block
Ans: Yes, nesting a try-catch block inside another try-catch is possible & valid. It can be nested inside another try block, catch block or finally block
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. For 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 connections & closing streams or file resources, etc. Finally, the 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 whether it’s handled or NOT
Can we have finally block followed by a try block (without a catch block)?
Ans: Yes, it is a valid sequence to have a try block followed by finally block (without a catch block or multiple blocks in between them)
Is it 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 the finally block But if there is a method that returns a value then writing any statement after the 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, the block is always executed irrespective of whether an exception is thrown or NOT, and whether it is handled or NOT But on one condition, finally won’t be executed when it encounters the System.exit(); method as it kills the program execution further
Will the finally block always be executed even if there is a return statement inside both the try block or catch block?
Ans: Yes, finally block is 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 the 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 raises an exception and this needs to be handled Otherwise, the program terminates abnormally
It is possible to declare a 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”. For example, as shown in the below screen capture
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
Method Description Format printStackTrace(); Prints all details related to an exception from an 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 the default exception handler to print the stack trace?
Ans: printStackTrace(); method of Throwable class
Throw & throws keywords and Custom Exception
Explain the throw keyword with its rules.
Ans: throw keyword:
Users 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 the throw keyword
Syntax: throw instanceOfThrowableType;
The main purpose of the throw keyword is to throw a user-defined exception or custom exception
Rules:
Both checked & unchecked exceptions can be thrown using the throw keyword. The caller method has to handle the exception whenever the target method declares an exception using the throw keyword. Any valid Java statement after the throw keyword is not reachable and it raises a compile-time error Whenever a thrown exception using the 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 the throw keyword after some alteration
Explain throws keyword with its rules.
Ans: throws keyword:
The throws keyword is used to declare the exception that might arise during program execution. whenever an exception might be thrown from the program, the programmer doesn’t necessarily need to handle that exception using a try-catch block instead simply declares that exception using the throws clause next to the method signature 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 an exception is declared using the throws clause by the target method, then the caller method must handle this exception type either try-catch block or declaring thrown exception type using the throws clause Any number of exceptions can be declared using the throws clause, but they 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 the throws keyword in the method signature?
Ans: Yes, it is possible to declare unchecked exceptions using throws clause
What happens if there are some Java statements after an explicit exception is thrown using the 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 exceptions 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
Is it valid to throw a Java object that doesn’t extend any Exception/Error from the 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 a normal Java object which isn’t extending any exception type from the 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 the throws keyword?
Ans: It’s an abnormal termination, irrespective of whether the program raises any exceptions or NOT, When we are using the 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 classes. 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 an exception is raised from a 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 the 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 reaches the bottom of the stack Checked exception isn’t propagated, the compiler forces the programmer to handle the checked exception in the same method by surrounding with try-catch block or declaring with the 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 it, instead, it wants to propagate the exception to the caller method (basically delegating the responsibility to the caller method) Sometimes, a method catches one type of exception and converts 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 is the responsibility of the caller method to handle this exception whether by surrounding it with try-catch or declaring the throws clause
What is the difference between throw and throws keywords?
Ans:
throw clause/keyword | throws clause/keyword |
---|---|
the throw keyword is used to throw an exception explicitly | throws 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 type | throws keyword is always followed by an exception list (with the comma separating them) |
A maximum of only one exception can be thrown using throw keywordThrown exception can be checked exception or unchecked exception or a user-defined exception | throws keyword is used next to the method signature |
Syntax: throw instanceOfExceptionType; | Syntax: access_modifier return_type method_name() throws exception_list; |
A maximum of only one exception can be thrown using the throw keywordThrown exception can be a checked exception unchecked exception or a user-defined exception | Any number of the exception can be thrown using throws keyword, but they are all separated by a comma (,) |
What is the difference between the try-catch block v/s throws keyword?
try-catch block | throws keyword |
---|---|
Using try-catch block, we can handle exception surrounding the code that might raise an exception | Whereas 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 alteration | There 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 exception | It doesn’t guarantee graceful termination. In most cases, throws declaration leads to abnormal termination |
Explain the difference between the final v/s and 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 the Object
Explain the difference between ClassNotFoundException v/s NoClassDefFoundError in detail.
ClassNotFoundException | NoClassDefFoundError |
---|---|
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.ClassNotFoundException | A fully qualified class name is java.lang.NoClassDefFoundError |
It falls under the category of Exception, i.e., a direct subclass of java.lang.Exception | It 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.1 | All 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 recoverable | The 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 the Java 1.7 version.
Ans: A new features introduced in the Java 1.7 version is, try-with-resources for automatic resource management multi-catch block for different grouping exception-type for similar handler code with pipe characters separating them
Explain the Automatic Resource Management feature in Java exception handling.
Ans: try-with-resources statement:
Using the try-with-resources statement, the programmer doesn’t need to close the opened resources explicitly Rather, they will be automatically closed once control reaches the end of the try-catch block This new feature introduced in the Java 1.7 version is alternatively referred to 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 the try block argument, but they all must be separated by the semi-colon (;)
While using the try-with-resources statement, the 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 variables declared inside the try block argument are implicitly final. Therefore, the resource reference variable can’t be changed or re-assigned within the try block
It is mandatory to follow the 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
How is a multi-catch block useful over traditional multiple-catch blocks?
Ans: Multi-catch block: In Java 1.6 or lesser version, whenever multiple exceptions are thrown, the programmer has to provide multiple catch blocks to catch different types of exceptions, 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 fewer lines of code
Rules: There shouldn’t be any relationship between the declared exception type in a multi-catch block. Otherwise, a 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 the exception variable is implicitly final Any changes or re-assignment to this implicit final variable within catch block results in a 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 the parent class method doesn’t declare any exception, Then the child class overriding method can declare any type of unchecked exception (this is the only possibility) If a child class overriding method declares a checked exception, the compiler throws a compile-time error stating “Exception IOException is not compatible with throws clause in ParentClass.testMethod()” Then the child class overriding method can declare no exception to the overriding method of the child class (very much the same as that of the overridden method in the parent class –> exactly same method signature)
Rule 2: If the parent class method declares an unchecked exception, Then the child class overriding method can declare any type of unchecked exception (not necessarily the same exception as that of the parent class method) If the child class overriding method declares any checked exception, then compiler throws a compile-time error stating “Exception IOException is not compatible with throws clause in ParentClass.testMethod()” Then the child class overriding method can declare no exception to the overriding method of the child class
Rule 3: If the parent class method declares a checked exception, Then the child class overriding method can declare any type of unchecked exception Then the child class overriding method can declare the same type of checked exception or one of its sub-class or no exception Then the child class overriding method can declare no exception in the overriding method of the child class
Rule 4: If the parent class method declares both checked & unchecked exceptions, Then the child class overriding method can declare any type of unchecked exception Then the child class overriding method can declare the same type of checked exception or one of its sub-class or no exception Then the 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 the throw clause When declaring multiple catch blocks, parent exception declared before the 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 an exception. The method can’t return an exception.