Exception handling in Java

One of the most effective ways to manage runtime failures while keeping the application's normal flow is to use Java's exception handling. Java Exception Handling handles ClassNotFoundException, IOException, SQLException, exception handling in java RemoteException, and other runtime difficulties.An object is created when a procedure throws an exception. The name given to this object is the exception object.

Learn More

It includes information concerning the exception, such as the error's name and description, as well as the state of the programme at the time the error occurred. To evaluate candidates' basic Java knowledge, many interviewers choose Java exception handling as one of their favoured topics.
In one piece, We've included the most commonly asked Java exception handling interview questions and answers.
I hope it becomes useful to you.

Exception Handling in Java

What is an Exception?

An exception is a rare occurrence that occurs during the execution of a programme and causes the normal flow of the program's instructions to be disrupted. It's a type of failure that occurs during the execution of a programme and causes the program's usual flow to be disrupted. It must be handled correctly, otherwise the programme will be abruptly terminated.

Here are a few examples:

🚀 User input that is not valid
🚀Failure of a device
🚀A network connection is lost.
🚀Physical restraints (out of disc memory)
🚀Code flaws
🚀Attempting to open a file that is currently unavailable

What is an Error?

Errors describe situations that are unrecoverable, such as the Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, and so on.
Errors are frequently outside the programmer's control, and we shouldn't try to fix them.

Difference between Error and Exception

An exception is a state from which it is possible to recover, but an error is an external situation from which it is usually impossible to recover.

All of the JVM's errors are instances of Error or one of its subclasses, with the following being the most common:

🚀OutOfMemoryError - thrown when the JVM can't allocate any more objects because it's out of memory and the garbage collector can't find any more.
🚀StackOverflowError - occurs when a thread's stack space is exhausted, usually as a result of an application recursing too far.
🚀ExceptionInInitializerError – indicates that during the execution of a static initializer, an unexpected exception occurred.
🚀NoClassDefFoundError – This error is thrown when the classloader tries to load the definition of a class but is unable to do so because the required class files are missing from the classpath.
🚀UnsupportedClassVersionError - occurs when the JVM tries to read a class file and concludes that the version is not supported, usually because the file was created with a newer version of Java.

While a try statement can be used to handle an error, it is not recommended because there is no guarantee that the programme will be able to do anything reliably after the error has been thrown.

Exception Hierarchy

All forms of exceptions and mistakes are subclasses of Throwable, which is the hierarchy's basic class. Exception is in charge of one branch. This class is used for unusual circumstances that user programmes should be aware of. The Java run-time system (JVM) uses another branch, Error, to identify issues related to the run-time environment (JRE). An example of such an error is StackOverflowError.

Types of Exceptions

Java defines a number of different types of exceptions for its various class libraries. Users can also define their own exceptions in Java.


Exceptions are classified in two ways:

🚀Exceptions that are built-in
🚀Exception that has been checked
🚀Exception that has been left unchecked
🚀Exceptions defined by the user

1. Built-in Exceptions: In Java libraries, built-in exceptions are exceptions that are available. These exceptions are appropriate for explaining specific mistake scenarios.
🚀Checked Exceptions: Checked exceptions are also known as compile-time exceptions since the compiler checks them at compile time.
Checked Exceptions vs. Unchecked Exceptions: Unchecked exceptions are the polar opposite of checked exceptions.
🚀Unchecked Exceptions: To put it another way, if a programme throws an unchecked exception, even if we don't handle or declare it, the programme won't throw a compilation error.

2. User-Defined Exceptions: In some cases, Java's built-in exceptions are unable to adequately explain a scenario. In such instances, users can design their own exceptions, known as 'user-defined Exceptions.'

The following are some of the benefits of using Exception Handling in Java:

🚀Provision for the completion of the program's execution
🚀Error Propagation and Easy Identification of Program Code and Error-Handling Code
🚀Identifying Error Types for Meaningful Error Reporting

What are the Exception Handling Keywords in Java?

In java exception handling, there are four keywords.

🚀throw: We may want to explicitly generate an exception object and then throw it to halt the program's usual operation. Throwing exceptions to the runtime for handling is done with the throw keyword.
🚀throws: When we throw a checked exception in a method and don't handle it, we must use the throws keyword in the method signature to inform the caller programme about the exceptions that the method may throw. Using the throws keyword, the caller method can either handle or propagate these exceptions to its caller method. The throws clause can contain numerous exceptions and can also be used with the main() method.
🚀In our code, we use the try-catch block to handle exceptions. To handle exceptions, try is at the beginning of the block and catch is at the end of the try block. With a try, we can have numerous catch blocks, and try-catch blocks can also be nested. A argument of type Exception is required for the catch block.
🚀finally: Finally is an optional block that can only be used with a try-catch block. Because throwing an exception halts the execution process, we may have resources open that will not be closed, therefore we can utilise the finally block. Whether or not an exception occurs, the finally block is always executed.

What are the important methods of Java Exception Class?

All of the methods in the base class Throwable are defined in Exception and all of its subclasses.

🚀String getMessage() — This method retrieves the message String of a Throwable, which can be specified when the exception is created using its function Object() { [native code] }.
🚀String getLocalizedMessage() – This method is provided so that subclasses can override it to send the calling application locale-specific messages. This method's throwable class implementation just uses the getMessage() function to return the exception message. s
🚀ynchronised Throwable getCause() – If the cause of the exception is unknown, this function returns null.
🚀String function toString() { [native code] }() — This method returns information about Throwable in String format, with the name of the Throwable class and a localised message.
🚀void printStackTrace() –This method is overloaded, and we can supply PrintStream or PrintWriter as an argument to send the stack trace information to a file or stream.

Explain Java 7 ARM Feature and multi-catch block?

If you catch a lot of exceptions in a single try block, you'll find that the catch block code is ugly and primarily consists of repetitive code to log the issue. With this in mind, one of Java 7's improvements was the multi-catch block, which allows us to catch numerous exceptions in one catch block.
We utilise finally blocks to close resources most of the time, but we sometimes fail to do so and get runtime exceptions when the resources are spent. These exceptions are difficult to debug, and we may need to check each location where we use that type of resource to ensure that it is closed. So try-with-resources was one of the advancements in Java 7, where we can construct a resource in the try statement and use it inside the try-catch block. The runtime environment automatically shuts these resources when the programme exits the try-catch block.

try (Resource m = new Resource()) {
            System.out.println("This Resource is created in try-with-resources");
          }  catch (Exception r) {

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

Checked Exceptions should be handled in the code with a try-catch block, or the method should utilise the throws keyword to inform the caller of any checked exceptions thrown by the method. Unchecked Exceptions do not need to be handled in the programme or mentioned in the method's throws clause.
The superclass of all checked exceptions is Exception, while the superclass of all unchecked exceptions is RuntimeException. It's worth noting that RuntimeException is a subclass of Exception.
Checked exceptions are error scenarios that must be addressed in the code or a compile time error will occur. If you use FileReader to read a file, for example, it will throw a FileNotFoundException, which we must catch in the try-catch block or throw to the caller method again. Poor programming, such as NullPointerException when running a method on an object reference without checking that it isn't null, is the most common cause of unchecked exceptions. For instance, I could create a method that removes all vowels from a string. It is the caller's responsibility to ensure that no null strings are passed. I may tweak the procedure to accommodate these circumstances, but the caller should ideally be responsible for this.

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

The throws keyword is used in conjunction with the method signature to declare any exceptions that the method may throw, whereas the throw keyword is used to interrupt the flow of the programme by giving the exception object to the runtime to handle.

How to write custom exceptions in Java?

To construct a new exception class, we can extend the Exception class or any of its subclasses. We can transmit error codes or other exception-related information to the exception handler using the custom exception class's variables and methods.

package com.journaldev.exceptions;

import java.io.IOException;

public class test extends Exception {

	private static final long serialVersion= = 466445699611218L;
	private String error_code="known_Exception";
	public test(String message, String error_code){
	public String getErrorCode(){
		return this.error_code;

What is OutOfMemoryError in Java?

In Java, OutOfMemoryError is a subclass of java.lang. JVM throws VirtualMachineError when it runs out of heap memory. We may fix this mistake by increasing the amount of memory available to the java application via java options.

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


The following are some examples of common main thread exception scenarios:

🚀java.lang thread main throws an exception.
🚀UnsupportedClassVersionError: This exception occurs when your java class was compiled with a different JDK version and you try to run it with a different JDK version.
🚀java.lang thread main throws an exception. This exception comes in two flavours: NoClassDefFoundError and NoClassDefFoundError.
🚀java.lang thread main throws an exception. main: NoSuchMethodError When you try to launch a class that doesn't have a main method, you'll get this exception.
🚀java.lang exception in thread "main" ArithmeticException: Whenever the main method throws an exception, the exception is printed to the console. The first section specifies that the main method throws an exception, the second part publishes the exception class name, and the third part prints the exception message after a colon.


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

In Java, final and finally are keywords, while finalise is a method.
Finally, the keyword can be used with class variables to prevent them from being reassigned, with the class to prevent it from being extended by other classes, and with methods to prevent subclasses from overriding them. Finally, the keyword can be used with the try-catch block to provide statements that will always be executed even if an exception occurs, and finally is usually used to close resources. Garbage Collector calls the finalise() method before destroying an object; it's an excellent approach to ensure that all global resources are closed.
Only the last of the three is related to java exception handling.

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

When a main() function throws an exception, Java Runtime stops the programme and sends the exception message and stack trace to the system console.

Can we have an empty catch block?

Although an empty catch block is permissible, it is an example of poor programming. We should never have an empty catch block since we will have no information about the exception if it is captured by that block, making debugging a headache. At the very least, a logging statement should be present to log the exception information in the console or log files.

Provide some Java Exception Handling Best Practices?

The following are some of the best practises for Java Exception Handling:

🚀To make debugging easier, use Specific Exceptions.
🚀Early in the programme, throw Exceptions (Fail-Fast).
🚀Exceptions should be caught late in the programme and handled by the caller.
🚀To ensure that resources are correctly closed, utilise the Java 7 ARM functionality or the finally block.
🚀Exception messages should always be logged for debugging purposes.
🚀For a cleaner closing, use a multi-catch block.
🚀To throw a single sort of exception from your application API, use custom exceptions.
🚀Keep the naming convention in mind, and always conclude with Exception.
🚀Exceptions should be documented. In javadoc, thrown by a function that uses @throws.
🚀Exceptions are costly, so use them only when necessary. Otherwise, you can intercept them and respond with a null or empty answer.

Can we keep other statements in between try, catch and finally blocks?

No. Between the try, catch, and finally blocks, no further statements should be written. They work together as a single entity.

    // Monitored Statement for exceptions
catch(Exception e)
    // exceptions are catching here
//You can't keep statements here
    // Always executed block

Can we write only try block without catch and finally blocks?

No, a compilation error is displayed. Either a catch or a finally block must come after the try block. Either the catch block or the finally block can be removed, but not both.

There are three statements in a try block – statement1, statement2 and statement3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in statement2. Does statement3 get executed or not?

No. If a try block throws an exception, the rest of the code will be skipped. The control is passed directly to the catch block.

What is unreachable catch block error?

When keeping several catch blocks, the order in which they are kept must be from the most specialised to the most generic. Exception subclasses must come first, followed by superclasses. If you put super classes first and sub classes second, the compiler will complain about an unreachable catch block.

What are run time exceptions in Java. Give example?

Run time exceptions are exceptions that occur during the execution of a programme. The compiler is unaware of these exceptions. All java.lang subclasses. java.lang and RunTimeException Errors are exceptions that occur during the execution of a programme. Unchecked exceptions are the type of exceptions we're talking about. NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError, and so on are examples of exceptions.

Can we keep the statements after finally block If the control is returning from the finally block itself?

It returns an inaccessible code fault. Because control is being sent back to the finally block. The statements after it will be ignored by the compiler.

Does finally block get executed If either try or catch blocks are returning the control?

Yes, regardless of whether or not the try or catch blocks return control, the finally block will always be executed.

Can we throw an exception manually? If yes, how?

It's Yes, The syntax for manually throwing an exception is as follows:
throw InstanceOfThrowableType;

What is Re-throwing an exception in Java?

The catch block handles exceptions raised in the try block. If it is unable to handle the exception, it can use the throw keyword to re-throw it. It's referred to as re-throwing an exception.

    String s = null;
catch(NullPointerException ex)
    System.out.println("NullPointerException is caught here");
   throw ex;  

Why it is always recommended that clean up operations like closing the DB resources to keep inside a finally block?

Because whether or not exceptions are raised in the try block and raised exceptions are captured in the catch block, the finally block is always executed. By putting the cleanup procedures in the finally block, you can ensure that they are always run, regardless of whether an exception occurs or not.

What is ClassCastException in Java?

When the JVM is unable to cast an object of one type to another type, it throws a ClassCastException.

What is StackOverflowError in Java?

When a stack overflows, the JVM throws an error called StackOverflowError.

Can we override a super class method which is throwing an unchecked exception with checked exception in the sub class?

No. If a super class method throws an unchecked exception, the sub class can override it with the same exception or any other unchecked exceptions, but not with checked exceptions.

Which class is the super class for all types of errors and exceptions in Java?

java.lang. In Java, Throwable is the superclass for all forms of exceptions and faults.

What are the legal combinations of try, catch and finally blocks?

    //try block
catch(Exception e)
    //catch block

    //try block
    //finally block

    //try block
catch(Exception e)
    //catch block
    //finally block

What is the use of printStackTrace() method?

The printStackTrace() function prints extensive information about the exception.

Give some examples to checked exceptions?

ClassNotFoundException, SQLException, IOException

Give some examples to unchecked exceptions?

NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

Do you know try-with-resources blocks? Why do we use them? When they are introduced?

From Java 7, try-with-resources blocks were introduced to automatically close resources utilised in the try block, such as File I/O streams, Database connections, and network connections. In your code, you don't have to explicitly close the resources. All resources used in the try block are implicitly closed by try-with-resources.

What are the benefits of try-with-resources?

The key advantage of using try-with-resources is that it prevents resource leaks from occurring if the resources are not correctly closed after use. Another advantage of using try-with-resources is that it eliminates unnecessary statements from the code, making it easier to comprehend.

What are the changes made to exception handling from Java 7?

From Java 7, two key modifications to exception handling are multi-catch exceptions and try-with-resources.

What does JVM do when an exception occurs in a program?

When JVM encounters an exception in a programme, it produces an exception object and throws it to notify us of the error. JVM will display an error message and terminate the rest of the application abnormally if the exception object is not caught and handled properly.

How do we catch an exception?

An exception can be caught in one of two ways. They are as follows:
By try-catch block
By using throws clause

What is throwing an exception in Java?

When a java program's method throws an exception, the method constructs an exception object (i.e., an object of the exception class) internally with the help of the JVM and passes it to the java runtime system (JVM). In Java, this is known as throwing an exception.

What is catching an exception in Java?

Catching an exception is the process of the JVM finding a handler to handle a thrown exception.

What will happen to exception object after exception handling is done?

The exception object will be trash collected once it has been handled.

How will you handle the checked exception?

A checked exception can be handled using either a try-catch block or the throws clause in the method declaration. It will generate a compile-time error if it is not handled properly.

Can we throw checked exceptions from the static block?

We can't throw because there's no designated catch area and it's only called once.

Why Would You Want to Subclass an Exception?

You should construct a custom exception if the exception type isn't already represented in the Java platform, or if you need to send more information to client code in order to treat it more precisely.
The decision to check or uncheck a custom exception is totally dependent on the business reason. As a general rule, if the code that uses your exception is anticipated to recover from it, make it a checked exception; otherwise, leave it unchecked.
You should also inherit from the most particular Exception subclass that closely resembles the one you're throwing. If no such class exists, select Exception as the parent.

What Are Some Advantages of Exceptions?

Traditional error detection and handling strategies can result in spaghetti code that is difficult to maintain and read. Exceptions, on the other hand, allow us to decouple our application's basic logic from the specifics of what to do when something unexpected occurs.
We also get the ability to propagate an error up the call stack without writing additional code since the JVM searches backward through the call stack for any methods interested in handling a particular exception.
Because all exceptions thrown in a programme are objects, they can be grouped or categorised according to the program's class structure. By defining the exception's superclass in the catch block, we can capture a bunch of exceptions in a single exception handler.

Points to remember:

🚀There may be more than one statement in a method that throws an exception, so place each of these statements in their own try block and provide a separate exception handler for each of them in their own catch block.
🚀If an exception occurs within the try block, the exception is handled by the associated exception handler.
🚀We must add a catch block after the exception handler to associate it. More than one exception handler is possible.
🚀Each catch block is an exception handler that deals with the type of exception specified in its argument.
🚀The ExceptionType parameter must be the name of the class that inherits from the Throwable class and indicates the sort of exception it may handle.
🚀There can be zero or more catch blocks for each try block, but only one final block. The finally block is not required.
🚀Whether or not an exception occurs in the try block, it is always executed.
🚀If an exception occurs, it will be handled after the try and catch blocks have been completed.
🚀If there isn't an exception, the code will be performed following the try block.
🚀In Java, the finally block is used to place critical code such as cleanup code, such as closing a file or disconnecting a connection.


1. When do Java exceptions appear in the code sequence?

2. Which of these keywords does not belong in the exception handling category?

3.Which of these keywords must be used to rationally handle the exception thrown by the try block?

4. Which of these terms should you use to keep an eye on for errors?

5. To manually throw an exception, which of these terms is used?



PHONE: +91 80889-75867

WhatsApp : Click Here...