Exception Handling Interview Questions

 Q1.What is an Exception in Java?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

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

handler to handle the exception. If no handler is found then the application throws the exception to the runtime environment and JRE terminates the program.

Java Exception handling framework is used to handle runtime errors only, compile-time errors are not handled by the exception handling framework.

Q2. What is the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

1) throw:

Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the program. The throw keyword is used to throw exceptions to the runtime to handle it. It is mainly used to throw a custom exception.

We can throw either checked or unchecked exceptions in Java by throw keyword.

read more

2) throws:

Throws is a keyword used to indicate that this method could throw this type of exception. 

The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions.

When we are throwing any checked exception in a method and not handling it, then we need to use the throws keyword in the method 

signature to let the caller program know the exceptions that might be thrown by the method. 

The caller method might handle these exceptions or propagate them to its caller method using the throws keyword. 

We can provide multiple exceptions in the throws clause and it can be used with the main() method also.

read more

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

read more

finally: The finally block is optional and can be used only with a try-catch block. 

Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use the finally block. The finally block gets executed always, whether an exception occurs or not.

read more

Q3. Explain Java Exception Hierarchy.

The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error.



Q4. Types of exception?

There are two types of exceptions in Java: checked (compile time) exceptions and unchecked (runtime) exceptions.

1) Checked exception (compile time exception)

Checked exceptions must be caught and handled during compile time. If the compiler does not see a try or catch block or throws a keyword to handle a checked exception, it throws a compilation error. Checked exceptions are generally caused by faults outside code like missing files, invalid class names, and networking errors.

Example

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Snippet {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("B:/dummy.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}


2) Unchecked exception (runtime exception)

Unchecked exceptions do not need to be explicitly handled; they occur at the time of execution, also known as run time. These exceptions can usually be avoided by good coding practices. They are typically caused by programming bugs, such as logic errors or improper use of APIs. These exceptions are ignored at the time of compilation.

For example:

public class Main {

    public static void main(String[] args) {

        int a = 5, b = 0;
       System.out.println(a / b);
       
    }

}


The example above will cause an ArithmeticException at the time of the program since a number can’t be divided by 0. It would throw an unhandled exception and the program would end.

3) Errors

People often refer to "errors" and “exceptions” as the same thing colloquially. However, in Java, these are separate concepts. Errors are thrown by the Java Virtual Machine and cannot be caught or handled. They derive from java.lang.Error and they occur because of some fault in the environment in which the application is running. For example, stack overflows and out-of-memory exceptions are environment errors that result in the application exiting.

4) Custom exceptions

Java’s built-in exceptions don’t always provide the information we need.  So, we sometimes need to supplement these exceptions with our own. During some specific operation, if an exception occurs in your application, you need to recover and make the user know about it.  A custom exception gives you more control to provide extra data about the problem and handle the exception in your code.

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception.  These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.

read more

Q5. What are the important methods of Java Exception Class?

Exception all of the methods are defined in the base class Throwable.

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

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

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

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

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

Q6. Multi-catch block exception handling?

If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the features was the multi-catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like the below:

catch(IOException | SQLException | Exception ex){
    logger.error(ex);
    throw new MyException(ex.getMessage());
}

read more


Q7. Try with resource exception handling

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvements was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of the try-catch block, the runtime environment automatically closes these resources. A sample of the try-catch block with this improvement is:

    try (MyResource mr = new MyResource()) {
        System.out.println("MyResource created in try-with-resources");
    } catch (Exception e) {
        e.printStackTrace();
    }


Q8. What is the difference between Checked and Unchecked Exceptions in Java?

Checked Exceptions should be handled in the code using a try-catch block or else the method should use the throws keyword to let the caller know about the checked exceptions that might be thrown from the method. Checked exceptions are error scenarios that require to be handled in the code, or else you will get compile time error. For example, if you use FileReader to read a file, it throws FileNotFoundException and we must catch it in the try-catch block or throw it again to the caller method.

Unchecked Exceptions are not required to be handled in the program or to mention in the throws clause of the method. Unchecked exceptions are mostly caused by poor programming, for example, NullPointerException when invoking a method on an object reference without making sure that it’s not null. For example, I can write a method to remove all the vowels from the string. It’s the caller’s responsibility to make sure not to pass a null string. I might change the method to handle these scenarios but ideally, the caller should take care of this.

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

throws keyword is used with the method signature to declare the exceptions that the method might throw whereas the throw keyword is used to disrupt the flow of the program and hand over the exception object to runtime to handle it.

Q10. How to write custom exceptions in Java?

We can extend the Exception class or any of its subclasses to create our custom exception class. The custom exception class can have its own variables and methods that we can use to pass error codes or other exception-related information to the exception handler. A simple example of a custom exception is shown below.

Example:

import java.io.IOException;

public class MyCustomeException extends IOException {

    private String errorCode = "1001";

    public MyCustomeException(String message, String errorCode) {

        super(message);

        this.errorCode = errorCode;

    }

    public String getErrorCode() {

        return this.errorCode;

    }

}


read more


Q11. What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options. like $>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

Q12. What are the different scenarios causing “Exception in thread main”?

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

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

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

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

Q13. What is the difference between final, finally, and finalize in Java?

final and finally are keywords in java whereas finalize is a method.

final keyword can be used with class variables so that they can’t be reassigned, with the class to avoid extending by classes, and with methods to avoid overriding by subclasses

finally keyword is used with try-catch block to provide statements that will always get executed even if some exception arises, usually finally is used to close resources.

finalize() method is executed by Garbage Collector before the object is destroyed, it’s a great way to make sure all the global resources are closed. Out of the three, only finally is related to java exception handling.

read more


Q14. What happens when an exception is thrown by the main method?

When an exception is thrown by a main() method, Java Runtime terminates the program and prints the exception message and stack trace in the system console.

Q15. Can we have an empty catch block?

Yes, We can have an empty catch block but it’s an example of bad programming. We should never have an empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in the console or log files.


Exception Handling Interview Questions

DBMS Interview Questions Set -1

DBMS Interview Questions Set -2

SQL Interview Question Set -1

SQL Interview Question Set -2

JPA Interview Questions Set -1

JPA Interview Question Set -2

Hibernate Interview Questions

Spring Boot Interview Questions Set 1

Spring Boot Interview Questions Set 2

GIT Interview Questions

Redis Interview Questions

Core Java Interview Questions Set -1

Docker interview question Set -1

Docker interview question Set -2

Kubernetes Interview Question Set -1

Kubernetes Interview Question Set -2

No comments:

Post a Comment