Types of Exception Handling in java with Example [2023]

Types of exception handling in java: There are two types of exceptions in Java: checked exceptions and unchecked exceptions.

Checked exceptions are those that the compiler forces you to handle or declare in a method signature using the ‘throws’ keyword. Some examples of checked exceptions are IOException, SQLException, and ClassNotFoundException.

Unchecked exceptions, on the other hand, are not required to be handled or declared by the compiler. These exceptions are usually caused by programming errors or logic errors in the code. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Here are some examples of how to handle exceptions in Java:

Types of exception handling in java

  1. Handling checked exceptions:
public void readFromFile() throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
    String line = reader.readLine();
    while (line != null) {
        System.out.println(line);
        line = reader.readLine();
    }
    reader.close();
}

In this example, the IOException is a checked exception that can be thrown by the FileReader and BufferedReader classes. Because it is a checked exception, the method signature includes the ‘throws’ keyword to indicate that the exception must be handled or declared.

  1. Handling unchecked exceptions:
public int divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    return a / b;
}

In this example, the divide method throws an unchecked ArithmeticException if the second parameter is zero. Because it is an unchecked exception, the method does not need to declare or handle the exception explicitly. Instead, the calling method can catch the exception if needed:

try {
    int result = divide(10, 0);
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());
}

This example shows how the calling method can catch the exception and handle it appropriately.

Types of exception in java

In Java, there are two types of exceptions: checked and unchecked exceptions.

  1. Checked exceptions: These exceptions are checked at compile-time, which means that the compiler checks if the exception is handled or not. If the exception is not handled, the code will not compile. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.
  2. Unchecked exceptions: These exceptions are not checked at compile-time, which means that the compiler does not force the programmer to handle them. Unchecked exceptions are also known as runtime exceptions. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

It’s important to note that all exceptions in Java inherit from the Exception class, which is a checked exception. However, the Runtime Exception class extends Exception and is used for unchecked exceptions.

Compile time exception in java

Compile time exceptions in Java are also known as checked exceptions. These exceptions are checked by the compiler during the compilation process, and the code will not compile if the exception is not handled properly.

Some examples of compile time exceptions in Java include:

  1. IOException – This exception occurs when there is an error reading or writing a file.
  2. ClassNotFoundException – This exception occurs when a class is not found while trying to load it dynamically.
  3. SQLException – This exception occurs when there is an error while accessing a database.
  4. InterruptedException – This exception occurs when a thread is interrupted while waiting or sleeping.
  5. IllegalAccessException – This exception occurs when a method or field is accessed illegally or without the proper access level.

To handle these exceptions, you can either use a try-catch block or declare the exception using the throws keyword in the method signature.

More Article Related To Core Java

Run time Exception in java

Runtime exceptions in Java are also known as unchecked exceptions. These exceptions are not checked by the compiler during the compilation process and occur at runtime. The code will still compile even if the exception is not handled properly.

Some examples of runtime exceptions in Java include:

  1. NullPointerException – This exception occurs when you try to access an object or variable that is null.
  2. ArithmeticException – This exception occurs when an arithmetic operation results in an error, such as dividing by zero.
  3. ArrayIndexOutOfBoundsException – This exception occurs when you try to access an array index that is out of bounds.
  4. IllegalArgumentException – This exception occurs when a method is passed an illegal or inappropriate argument.
  5. ClassCastException – This exception occurs when an object is cast to a type that it is not compatible with.

To handle these exceptions, you can use a try-catch block, but it is not required. It is recommended to handle runtime exceptions, but it is not mandatory like checked exceptions. It is also important to note that all runtime exceptions inherit from the Runtime Exception class in Java.

Exception interview questions in java

Here are some common interview questions related to exceptions in Java:

  1. What is an exception in Java?
  2. What are the different types of exceptions in Java?
  3. What is the difference between checked and unchecked exceptions in Java?
  4. What is the purpose of try-catch block in Java?
  5. Can a catch block have multiple exceptions in Java? If yes, how do you handle them?
  6. What is the purpose of the finally block in Java?
  7. What happens if an exception is not caught in Java?
  8. How do you create a custom exception in Java?
  9. What is the difference between throw and throws in Java?
  10. How do you handle exceptions in a multi-threaded program in Java?

These questions will help you test your knowledge of Java exceptions and demonstrate your understanding of the subject during an interview.

How do you create a custom exception in Java?

In Java, you can create your own custom exception by extending the Exception class or any of its subclasses. Here are the steps to create a custom exception:

  1. Create a new class that extends the Exception class or any of its subclasses, such as RuntimeException.
  2. Define a constructor for the custom exception class that calls the constructor of its superclass using the super() keyword. You can also add additional constructors to the class as needed.
  3. Add any custom fields or methods to the class as needed.
  4. Use the custom exception in your code by throwing it when the situation warrants it.

Here is an example code snippet that demonstrates how to create a custom exception class in Java:

public class CustomException extends Exception {

    public CustomException() {
        super();
    }

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomException(Throwable cause) {
        super(cause);
    }

    // Add any custom fields or methods as needed
}

Once you have defined your custom exception class, you can use it in your code by throwing it when necessary:

public void someMethod() throws CustomException {
    // Throw custom exception when something goes wrong
    throw new CustomException("Something went wrong!");
}

In the above example, the some Method() throws the custom exception when something goes wrong, and the calling code will need to handle the exception appropriately.

What is the purpose of the finally block in Java?

The finally block in Java is used to ensure that a section of code is always executed, regardless of whether an exception is thrown or not. The finally block is used in combination with the try-catch block.

The purpose of the finally block is to provide a clean-up mechanism for any resources that were acquired or allocated in the try block, such as file streams, database connections, or network sockets. The finally block is also used to close any resources that were left open in the try block.

The syntax of a try-catch-finally block in Java is as follows:

try {
    // Code that may throw an exception
} catch (Exception e) {
    // Code to handle the exception
} finally {
    // Code that will always be executed, regardless of whether an exception was thrown or not
}

Here’s an example to illustrate the use of the finally block in Java:

FileInputStream input = null;
try {
    input = new FileInputStream("file.txt");
    // Code to read from the file
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + e.getMessage());
} finally {
    if (input != null) {
        try {
            input.close(); // Close the input stream in the finally block
        } catch (IOException e) {
            System.out.println("Error closing file: " + e.getMessage());
        }
    }
}

In the above example, the try block is used to open a file input stream and read from the file. The catch block is used to handle any exceptions that may be thrown when attempting to read from the file. The finally block is used to close the input stream, regardless of whether an exception was thrown or not.

In summary, the finally block in Java is used to ensure that a section of code is always executed, regardless of whether an exception is thrown or not. It is typically used to release resources that were acquired or allocated in the try block.

What is the difference between error and exception in Java interview questions?

In Java, errors and exceptions are both subclasses of the Throwable class, but they have different meanings and use cases.

  1. Error: An error is an exceptional condition that typically cannot be recovered from. Errors are caused by problems outside of the control of the program, such as running out of memory or a hardware failure. Errors are generally considered fatal and cannot be caught or handled in a try-catch block. Examples of errors in Java include OutOfMemoryError and StackOverflowError.
  2. Exception: An exception is an exceptional condition that can be handled by the program. Exceptions are caused by errors within the program, such as incorrect input or I/O errors. Exceptions can be caught and handled using try-catch blocks, and they are generally considered recoverable. In Java, there are two types of exceptions: checked exceptions and unchecked exceptions. Checked exceptions are checked at compile-time, while unchecked exceptions are not. Examples of exceptions in Java include NullPointerException and FileNotFoundException.

In summary, errors and exceptions in Java are both subclasses of the Throwable class, but errors are typically caused by external factors outside of the program’s control and are considered fatal, while exceptions are caused by errors within the program and can be recovered from by handling them in a try-catch block.

Top Interview Questions & Answers

Java Exception Handling Interview Questions and Answers

Here are some Java Exception Handling interview questions and answers:

Q.1 What is exception handling in Java?

Answer: Exception handling is the process of handling and responding to exceptions that occur during the execution of a Java program. Exceptions are events that occur during the program’s execution that disrupt the normal flow of control.

Q.2 What is the difference between checked and unchecked exceptions in Java?

Answer: Checked exceptions are checked at compile-time and are usually caused by external factors outside of the program’s control, such as I/O errors or database errors. Unchecked exceptions are not checked at compile-time and are usually caused by programming errors, such as null pointer exceptions or array index out of bounds exceptions.

Q.3 What is the purpose of try-catch blocks in Java?

Answer: Try-catch blocks are used to handle exceptions that may occur during the execution of a Java program. The code that may throw an exception is placed within the try block, and the code that handles the exception is placed within the catch block.

Q.4 Can multiple catch blocks be used for a single try block in Java?

Answer: Yes, multiple catch blocks can be used for a single try block in Java. Each catch block must specify the type of exception it can handle.

Q.5 What is the purpose of the finally block in Java?

Answer: The finally block in Java is used to ensure that a section of code is always executed, regardless of whether an exception is thrown or not. The finally block is used in combination with the try-catch block.

Q.6 How do you create a custom exception in Java?

Answer: To create a custom exception in Java, you must create a new class that extends the Exception class. You can then define the behavior of the custom exception by overriding the methods in the Exception class.

Q.7 How can you catch multiple exceptions in a single catch block in Java?

Answer: In Java 7 and later, you can catch multiple exceptions in a single catch block by using a multi-catch statement. You can specify multiple exceptions in the catch block by separating them with a pipe symbol (|).

Q.8 Can you throw an exception from a catch block in Java?

Answer: Yes, you can throw an exception from a catch block in Java. However, it is important to handle any exceptions that may occur while throwing the new exception.

Q.9 What is the difference between throw and throws in Java?

Answer: The throw keyword is used to explicitly throw an exception from a method, while the throws keyword is used to declare that a method may throw one or more exceptions.

Q.10 What is the difference between System.exit(0) and System.exit(1) in Java?

Answer: System.exit(0) indicates a successful termination of the program, while System.exit(1) indicates an unsuccessful termination of the program due to an error or exception.

Latest Drive Update To Join Telegram Channel Given Below Link

Join TelegramPSA Student Join Now
Home PageFull Stack With Java
PSA New Batch LinkClick Here

Leave a Comment