6.What is an ArrayIndexOutOfBoundsException in Java?
An ArrayIndexOutOfBoundsException is thrown when your program tries to access an element of an array using an invalid index. This is the case either when the index is negative or is greater than or equal to the size of the array.
Example
public class ArrayIndexOutOfBoundsExample {
public void accessArray() {
int[] arr = new int[5];
arr[10] = 100; // This will throw an ArrayIndexOutOfBoundsException
}
Here, the size of array arr is 5 and tries to access 10th which does not exist. You could even check the index prior to accessing the array as follows:
public void accessArraySafely(int index) {
int[] arr = new int[5];
if (index >= 0 && index < arr.length) {
arr[index] = 100;
} else {
System.out.println("Index is out of bounds");
}
}
Validating array indices will save you from runtime errors and ensure that your code runs flawlessly without crashes at runtime.
7.What is a Java ClassNotFoundException and How Does It Come About?
ClassNotFoundException occurs when JVM or a class loader tries to load a class, but fails to locate a required.class file. This type of error mainly occurs while attempting to load the class dynamically as by using a Class.forName() method, yet the class could not be available in the classpath.
Let's consider this example:
public class ClassNotFoundExceptionExample
{
public void loadClass() {
try {
Class.forName("com.example.MissingClass");
} catch (ClassNotFoundException e)
{
System.out.println("Message-Class not found: " + e.getMessage());
}
}
}
In this code, an attempt is made to load the com.example.MissingClass, which doesn’t exist. As a result, a ClassNotFoundException is triggered. To prevent this error ensure all required classes are included in the classpath.
8.What is an IOException in Java and How Can You Handle It?
An IOException is a checked exception indicating an error from input or output operations. Typical causes of IOExceptions are file I/O, network communication and access to peripheral hardware. Because it is a checked exception, it is necessary to either explicitly handle it or throw it in the method declaration.
Here is an example:
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public void readFile() throws IOException {
FileReader reader = new FileReader("missing_file.txt");
reader.read();
}
}
Handling an IOException is done using a try catch block as shown below:
try {
readFile();
} catch (IOException e) {
System.out.println("Error while Reading file: " + e.getMessage());
}
This ensures that if there is an error while the program is dealing with files or other resources, it can continue running.
9.What is a FileNotFoundException and How Do You Handle It?
FileNotFoundException is a subclass of IOException. This exception appears when an attempt to open any file operation involves the specified file which does not exist or is unavailable. This also happens to be a checked exception; therefore it has to either be declared and caught in a method.
Let's consider a simple example on this.
import java.io.FileReader;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionExample {
public void openFile() throws FileNotFoundException {
FileReader reader = new FileReader("wrong_file_name.txt"); /* Raise FileNotFoundException */
}
}
To handle this, wrap the operation in a try catch block:
try {
openFile();
} catch (FileNotFoundException e) {
System.out.println("The file dose it exist: " + e.getMessage());
}
You can also check if the file exists beforehand to prevent this exception.
10.What is an SQLException in Java and How Do You Handle Database Errors?
An SQLException is the indication of some error in the database operations. This can happen due to errors in SQL queries, problems in connection or constraint violations. Like all other checked exceptions it needs either to be declared or handled explicitly.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLExceptionExample {
public void connectToDatabase() throws SQLException {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/databaseName", "username", "password");
// Here your database operations go
}
}
To handle this exception, use the following try-catch block:
try {
connectToDatabase();
} catch (SQLException e) {
System.out.println("Error in Database connection : " + e.getMessage());
}
Always close database resources after use to avoid resource leaks and maintain efficiency.
11.What is the Try-With-Resources Statement in Java?
The try-with-resources statement makes resource management in Java much simpler. Added in Java 7, this statement automatically closes resources such as files, database connections, or streams used in a try-with-resources block even if an exception is thrown. Any resource used in a try-with-resources block must implement AutoCloseable or Closeable.
For example
import java.io.FileReader;
public class TryWithResourceExample {
public void readFile() {
try (FileReader reader = new FileReader("example_file.txt")) {
int data = reader.read();
System.out.println((char) data);
}
catch (IOException e) {
System.out.println("Error while reading the file: " + e.getMessage());
}
}
In the above example, the FileReader closes automatically when the try block gets over. There is no requirement of finally block to close the resource, so it reduces a lot of messy code.
12.What are the Advantages of Java Custom Exceptions?
Custom exceptions mean that you can design an application specific error. The problem that has just arisen can thus be addressed more intuitively and meaningfully as it is a business logic related application error.
Some advantages include:
More descriptive error handling is made easy by the clarity of the name given to your custom exceptions along with corresponding descriptions that may symbolize the actual business logic contained in your application.
Better Control: You can make error handling as per your application's requirement so that it provides more accurate and efficient responses to the problems.
Carrying Extra Information: Custom exceptions can carry more information, for example, error codes or more detailed messages. This makes debugging easier and can improve logging.
Here is how you can implement it:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
Now, instead of using generic exceptions, it is possible to use InsufficientFundsException for the particular case, like insufficient balance in an account as the error handling can be made more clear and specific.
13.How do you log exceptions in Java for better debugging?
Logging is an essential operation when debugging and maintaining applications, especially in production. Java provides powerful logging APIs like java.util.logging, log4j and SLF4J to log error information in files, consoles or remote systems.
Example using java.util.logging:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggingExceptionExample {
private static final Logger logger = Logger.getLogger(LoggingExceptionExample.class.getName());
public void readFile() {
try {
throw new IOException("File not found");
}
catch (IOException e) {
logger.log(Level.SEVERE, "Error reading file", e);
}
}
}
This is how, in the code above, a logger catches an exception with a SEVERE level. This makes it easy as a developer to point out where problems are happening. In general, error analysis will be easier like that.
14.How do you rethrow an exception in Java? Why would you ever want to do that?
Rethrowing an exception will enable you to pass it up the call stack when you cannot handle it at this level. This would give higher level methods the opportunity to address the issue or it can log or report appropriately.
Here is an example:
public class RethrowExceptionExample {
public void readFile() throws IOException {
try{
/* Code that might throw an exception*/
throw new IOException("File not found");
}
catch (IOException e) {
System.out.println("Handling IOException");
throw e; /* Passing it up the call stack */
}
}
}
This is very useful when your method does not have the context or capability to resolve the issue but wants to ensure it doesn't go unhandled.
15.What Is the Throwable Class in Java and How Is It Related to Exceptions and Errors?
The Throwable class is the base class for all exceptions and errors in Java. It has two main branches:
Exceptions: These are the issues that the program can detect and handle like IOException or NullPointerException.
Errors: These are more critical issues, such as OutOfMemoryError that is mostly beyond the program's control and also indicates critical issues in the JVM.
Throwable offers useful methods such as getMessage() to retrieve details of the error and printStackTrace() to print where the issue occurred.
Here is a brief example:
try {
throw new NullPointerException();
}
catch (Throwable t) {
System.out.println(t);
}
Catch and print any Throwable While Throwable can catch both exceptions and errors, you should avoid catching Error instances unless you have a very specific reason as they often indicate critical failures like memory or system limitations.
16.How to Create a Chain of Exceptions in Java (Exception Chaining)?
Exception chaining is the association of one exception with another. It lets you provide more context while still preserving information about the original problem. It aids in debugging and tracking the root cause of an error. This is achieved by passing the original exception as the cause to a new exception.
Example:
public class ExceptionChainingExample{
public void processFile() {
try{
// Simulate an IOException
throw new IOException("File dose not available!");
}
catch (IOException e) {
/* Wrap the IOException inside a RuntimeException*/
throw new RuntimeException("Error has been occurred during file processing", e);
}
}
}
This code includes the cause of the exception as IOException and the RuntimeException. When an exception is logged, it will display a detailed trace of both new and original exceptions, making debugging easier.
17.What is difference Between throw and throws in Java?
The words throw and throws seem to be used interchangeably. However, the purpose they serve in Java is different.
throw: The keyword is used inside a method to explicitly create an exception. The throw keyword can be used to throw both checked and unchecked exceptions.
Example:
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age is not valid and must be at least 18");
}
}
throws: This is used in the method declaration to indicate that the method might generate specific exceptions. It serves as a warning to the caller to handle or propagate the exceptions.
Example:
public void readData() throws IOException {
FileReader fileReader = new FileReader("my_demo_file.txt");
}
Summary:
Use throw to throw an exception in your code.
Use throws in the method signature to declare potential exceptions that might be encountered.
18.How do you catching Throwable in Java and Why It's Discouraged?
You can catch Throwable using a try-catch block because it is the superclass of all exceptions and errors in Java, but this is discouraged because you catch both Exception and Error including critical system errors like OutOfMemoryError which are usually not recoverable and may destabilize your application.
Example:
try {
/* Code that might cause an exception or error */
}
catch (Throwable t) {
System.out.println("Exception Throwable Caught: " + t.getMessage());
}
Why Avoid It?
Throwing and catching Throwable may lead to unexpected behavior, such as attempting to recover from a fatal error. Instead, catch only those exceptions that are appropriate to your application's logic.
19.Waht is difference Between Exception and Error in Java?
Exception and Error are two different classes of the throwable class in Java, used for different purposes.
Exception Example In most cases, such circumstances can often be foreseen and controlled. For example, invalid user input and missing files.
There are two categories:
Checked exceptions: These need to be declared in the method signature or explicitly caught (like IOException).
Unchecked exceptions: No explicit catching is required, and these are often residuals of programming mistakes (like NullPointerException).
Error: These are the most critical problems, usually resulting from some environmental problem or the JVM. Typical examples include OutOfMemoryError and StackOverflowError. These are normally not recoverable and it is not advisable to catch and handle them.
Example:
try {
throw new Exception("A recoverable problem has occurred");
}
catch (Exception e) {
System.out.println(" an exception has caught: " + e.getMessage());
}
try {
throw new Error("Critical system failure");
}
catch (Error e){
System.out.println("Caught an error: " + e.getMessage());
}
Key Point:
Exceptions are something that the application can handle but errors represent major failure and are best left to the JVM.
20.Exception Handling in Multithreaded Programs of Java
In Java's multi-threaded applications exception handling must account for each thread operating independently. If a thread encounters an exception it will not affect other threads, but it's important to handle exceptions within each thread or globally.
Handling Exceptions in a Thread's run() Method:
public class ThreadWithExceptionHandling extends Thread {
public void run() {
try {
// Simulating error in thread
throw new RuntimeException("Thread related issue occurred!");
}
catch(RuntimeException e){
System.out.println("Error Occurred in thread: "+e.getMessage());
}
}
public static void main(String[] args) {
Thread thread = new ThreadWithExceptionHandling();
thread.start();
}
}
Using a Global Exception Handler:
Java allows setting a default handler for uncaught exceptions across all threads using
setDefaultUncaughtExceptionHandler().
Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
System.out.println("Unhandled exception in thread " + thread.getName() + ": " + exception.getMessage());
});
Previous Topic==> Basic Exceptions in Java FAQ. || Next Topics==> Advanced Exceptions in Java FAQ
Other Topic==>
Banking Account Management Case Study in SQL
Top SQL Interview Questions
Employee Salary Management SQL FAQ!. C FAQ
Top 25 PL/SQL Interview Questions
Joins With Group by Having
Equi Join
Joins with Subqueries
Self Join
Outer Join