1. What is Exception in Java?
An Exception in Java is an event that disrupts the normal flow of a program’s execution. It typically represents an error or an unexpected situation, such as invalid input or system failure. When an exception occurs, it can be caught and handled using try-catch blocks, allowing the program to continue running or fail gracefully. There are two types of exceptions: checked exceptions (which must be declared or handled) and unchecked exceptions (which are usually caused by programming errors).
2. How the exceptions are handled in Java?
Exceptions are handled using try-catch blocks. Here’s how it works:
- Try block: Code that may throw an exception is placed inside the try block.
- Catch block: If an exception occurs, the catch block is executed to handle the exception.
- Finally block: (Optional) Code that must always execute, regardless of whether an exception occurred, is placed in the finally block.
3. What is the difference between error and exception in Java?
The main difference between error and exception is:
- Error: These are serious issues that typically can’t be handled by the program, such as system-level problems (e.g., OutOfMemoryError or StackOverflowError). Errors usually indicate problems that are beyond the control of the application.
- Exception: These are conditions that a program can handle or recover from, such as invalid user input or file not found (e.g., IOException or NullPointerException). Exceptions can be caught and handled using try-catch blocks.
4. What is the difference between checked and unchecked exceptions?
The difference between checked and unchecked exceptions is:
- Checked Exceptions: These are exceptions that must be either caught or declared in the method signature using the throws keyword. They are checked at compile-time. Examples include IOException and SQLException.
- Unchecked Exceptions: These are exceptions that are not required to be caught or declared. They are usually caused by programming errors, such as accessing a null object or array out-of-bounds. These are checked at runtime. Examples include NullPointerException and ArrayIndexOutOfBoundsException.
5. Explain the hierarchy of exceptions in Java?
In Java, the exception hierarchy is as follows:
- Throwable: The root class for all errors and exceptions in Java.
- Error: Represents serious problems that applications should not try to catch (e.g., OutOfMemoryError, StackOverflowError).
- Exception: Represents conditions that a program may catch and handle.
- Checked Exceptions: Subclasses of Exception that are checked at compile-time and must be handled (e.g., IOException, SQLException).
- Unchecked Exceptions: Subclasses of RuntimeException that are not required to be handled or declared (e.g., NullPointerException, ArrayIndexOutOfBoundsException).
6. Explain the purpose of the ‘try’, ‘catch’, and ‘finally’ blocks?
The purpose of the ‘try’, ‘catch’, and ‘finally’ blocks is to handle exceptions and ensure the program runs smoothly:
- try block: Contains the code that might throw an exception. It is used to wrap the code that could potentially cause an error.
- catch block: Used to handle the exception that is thrown in the try block. If an exception occurs, the corresponding catch block catches it and provides a way to handle or log the error.
- finally block: Contains code that will always execute, regardless of whether an exception was thrown or not. It’s typically used for cleanup tasks (like closing files or releasing resources).
7. Can you have multiple ‘catch’ blocks for a single ‘try’ block?
Yes, in Java, you can have multiple ‘catch’ blocks for a single ‘try’ block. This allows you to handle different types of exceptions separately.
For example:
try { // Code that may throw exceptions } catch (IOException e) { // Handle IOException } catch (SQLException e) { // Handle SQLException } catch (Exception e) { // Handle other exceptions } Each ‘catch’ block can handle a specific type of exception, and the order should go from more specific to more general exceptions (e.g., IOException before Exception). |
8. Can we keep other statements in between try, catch and finally blocks?
No, you cannot place other statements between the try, catch, and finally blocks. The structure must follow this specific order:
- try block
- catch block(s)
- finally block (optional)
Each block has a distinct purpose, and they must appear in this order without any other statements in between. For example:
try { // Code that may throw an exception } catch (Exception e) { // Handle exception } finally { // Cleanup code } You can’t add other statements between the blocks. |
9. Can we write only try block without catch and finally blocks?
Yes, in Java, you can write a try block without a catch or finally block, but only if the try block is followed by a ‘throw’ statement or in situations where the exception is declared to be thrown by the method using the throws keyword.
For example:
try { // Code that may throw an exception throw new Exception(“Example Exception”); } catch (Exception e) { // Handle exception } |
10. Give an example of a checked exception in java?
Here are some common checked exceptions in Java:
- FileNotFoundException
- SQLException
- ParseException
- InterruptedException
- NoSuchMethodException
- CloneNotSupportedException
- UnsupportedEncodingException
- IOException
- RemoteException
- ClassNotFoundException
11. What is the throws keyword in Java?
The throws keyword in Java is used in a method declaration to indicate that the method may throw one or more exceptions. It passes the responsibility of handling the exception to the caller.
Example:
public void readFile() throws IOException { // Code that may throw IOException } |
12. What is the difference between throw and throws in Java?
- throw: Used to explicitly throw an exception from within a method or block of code.
Example: throw new IOException(“File not found”);
- throws: Used in a method signature to declare that the method may throw one or more exceptions, passing the responsibility to handle them to the caller.
Example: public void readFile() throws IOException {}
13. Give an example of a unchecked exception in java?
Here are some common unchecked exceptions in Java:
- ArrayIndexOutOfBoundsException: Occurs when accessing an invalid index in an array.
- ArithmeticException: Occurs during invalid arithmetic operations, like division by zero.
- IllegalArgumentException: Occurs when a method receives an invalid argument.
- IllegalStateException: Occurs when a method is called at an inappropriate time.
- IndexOutOfBoundsException: Occurs when accessing an invalid index in a collection.
- UnsupportedOperationException: Occurs when an operation is not supported.
- ConcurrentModificationException: Occurs when a collection is modified during iteration.
- NullPointerException: Occurs when trying to use a null reference.
- ClassCastException: Occurs when an invalid type cast is attempted.
- NumberFormatException: Occurs when parsing a non-numeric string to a number.
14. What is the use of the finally block?
The finally block in Java is used to define code that will always be executed, regardless of whether an exception is thrown or not. It’s typically used for cleanup operations, such as closing files, releasing resources, or closing database connections.
Example:
try { // Code that may throw an exception } catch (Exception e) { // Exception handling } finally { // Code that always runs, even if an exception occurs System.out.println(“Cleanup operations.”); } |
15. What is the difference between RuntimeException and Error in Java?
The difference between RuntimeException and Error is:
- RuntimeException: A subclass of Exception, it represents exceptions that can occur during the normal operation of the Java Virtual Machine (JVM). These are typically caused by programming mistakes, such as NullPointerException or ArrayIndexOutOfBoundsException. These exceptions are unchecked and don’t need to be declared or caught.
- Error: Represents serious issues that occur in the JVM, such as OutOfMemoryError or StackOverflowError. Errors are usually beyond the control of the program, and the program should not try to handle them.
16. How to handle multiple exceptions in Java?
Multiple exceptions can be handled using:
- Multiple catch blocks: You can use separate catch blocks to handle different exceptions individually.
Example:
try { // Code that may throw exceptions } catch (IOException e) { // Handle IOException } catch (SQLException e) { // Handle SQLException } |
17. What are run time exceptions in Java. Give example?
Runtime exceptions in Java are exceptions that occur during the execution of the program, usually due to programming errors. These are unchecked exceptions, meaning they do not need to be declared or caught explicitly.
Example:
public class RuntimeExceptionExample { public static void main(String[] args) { String str = null; System.out.println(str.length()); // This will throw NullPointerException (a runtime exception) } } |
Common examples of runtime exceptions:
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArithmeticException
18. What is OutOfMemoryError in Java?
OutOfMemoryError in Java is an Error that occurs when the Java Virtual Machine (JVM) runs out of memory, typically due to excessive memory consumption or memory leaks in the application. This error indicates that the JVM is unable to allocate memory for new objects.
19. What is the difference between ClassNotFoundException and NoClassDefFoundError in Java?
Aspect | ClassNotFoundException | NoClassDefFoundError |
Type | Exception (checked) | Error (unchecked) |
Cause | Thrown when the JVM cannot find a class at runtime while dynamically loading it using Class.forName() or similar methods. | Thrown when a class was available during compile-time but is missing at runtime (e.g., classpath issues). |
Occurs | During runtime when trying to load a class dynamically that is not available. | When the JVM fails to find a class that was previously available but is no longer found during runtime. |
Handling | Must be handled using a try-catch block because it’s a checked exception. | Cannot be caught using a try-catch block, as it’s an unchecked error. |
Example | Class.forName(“com.example.MyClass”); | Class file missing from the classpath, causing error when JVM attempts to load it. |
20. Can we keep the statements after finally block If the finally block is returning the control?
No, if the finally block returns control using a return statement, then any statements written after the finally block become unreachable and will cause a compilation error.
21. Does finally block get executed If either try or catch blocks are returning the control?
Yes, the finally block always gets executed even if the try or catch block has a return statement, unless the JVM is shut down (e.g., with System.exit()).
22. What is a StackOverflowError in Java?
A StackOverflowError in Java occurs when a program recurses too deeply, exceeding the call stack limit. It usually happens due to infinite or very deep recursion.
23. What is custom exception in Java and how do you create one?
A custom exception in Java is a user-defined exception created by extending the Exception or RuntimeException class to handle specific application errors.
How to create:
class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } } |
24. What is the exception chaining in Java?
Exception chaining in Java is the process of linking one exception to another using the cause of an exception, to preserve the original error information.
Example:
try { // Some code that throws IOException } catch (IOException e) { throw new RuntimeException(“Failed to process file”, e); // chaining } |
25. What happens if an exception is not caught?
If an exception is not caught, the program will terminate, and the JVM will print a stack trace showing where the exception occurred.
26. What is the ArithmeticException and when is it thrown?
ArithmeticException is a runtime exception in Java thrown when an illegal arithmetic operation is performed, such as dividing by zero.
Example:
int result = 10 / 0; // Throws ArithmeticException |
27. What is the difference between final, finally and finalize in Java?
Keyword | Type | Purpose |
final | Keyword | Used to declare constants, prevent method overriding or inheritance. |
finally | Block | Used to execute code after try/catch, always runs, for cleanup. |
finalize() | Method | Called by the garbage collector before an object is destroyed (deprecated). |
28. What is ClassCastException in Java?
ClassCastException in Java is a runtime exception thrown when you try to cast an object to a class it’s not an instance of.
Example:
Object obj = new String(“Hello”); Integer num = (Integer) obj; // Throws ClassCastException |
29. What are the benefits of using checked exceptions over unchecked exceptions in Java?
The Benefits of using checked exceptions over unchecked exceptions in Java:
- Compile-time checking: Checked exceptions must be either caught or declared, ensuring that potential errors are handled or acknowledged by the programmer at compile-time.
- Improved reliability: Helps in handling expected errors (like file I/O or database issues) explicitly, reducing the risk of runtime failures.
- Clearer code intention: Makes the code more robust by forcing the developer to deal with exceptional conditions that might occur during execution.
30. What is a NullPointerException, and how can it be avoided in Java?
NullPointerException in Java is a runtime exception that occurs when you try to use a reference variable that points to null (e.g., calling a method or accessing a field on a null object).
Example:
String str = null; int length = str.length(); // Throws NullPointerException |
How to avoid:
Check for null before accessing the object: if (str != null) { int length = str.length(); } |
31. What is the difference between throw and throws when handling exceptions in Java?
throw: Allows a programmer to explicitly raise an exception in the program’s flow, usually in response to some invalid input or condition.
Example:
throw new IllegalArgumentException(“Invalid argument!”); |
throws: Declares that a method might throw one or more exceptions, signaling to the caller that they should be prepared to handle these exceptions.
Example:
public void readFile(String fileName) throws IOException { // method logic } |
32. Can an exception propagate across multiple methods?
Yes, an exception can propagate across multiple methods in Java. If an exception is not caught in a method, it will be passed (propagated) to the calling method. This continues until the exception is caught or it reaches the main() method, where it can terminate the program if not handled.
33. What is the ClassNotFoundException in Java, and how is it handled?
ClassNotFoundException in Java is a checked exception that occurs when the JVM tries to load a class by its name (e.g., using Class.forName()) and cannot find the class in the classpath.
Example :
try { Class.forName(“com.example.NonExistentClass”); } catch (ClassNotFoundException e) { System.out.println(“Class not found: ” + e.getMessage()); } How to handle: It must be caught using a try-catch block, as it is a checked exception. |
34. What happens if an exception is thrown from a finally block?
If an exception is thrown from a finally block, it overrides any exception that was thrown in the try or catch block. The exception from the finally block will be propagated and can be the one that is ultimately reported.
Example :
public class FinallyExceptionExample { public static void main(String[] args) { try { throw new Exception(“Exception in try”); } catch (Exception e) { System.out.println(e.getMessage()); } finally { throw new RuntimeException(“Exception in finally”); } } } |
Output :
Exception in try Exception in thread “main” java.lang.RuntimeException: Exception in finally |
35. Can we have multiple finally blocks in a single method?
No, you cannot have multiple finally blocks in a single method. A method can only have one finally block that follows the try and catch blocks.
Example :
public class MultipleFinallyExample { public static void main(String[] args) { try { System.out.println(“In try block”); } catch (Exception e) { System.out.println(“In catch block”); } finally { System.out.println(“In first finally block”); } // The following line will cause a compilation error // finally { // System.out.println(“In second finally block”); // } } } |