EXCEPTION
EXCEPTION
What are Exceptions in Java? An exception is an event in Java that disrupts the normal
flow of a program. It indicates an error or abnormal condition, which can be handled using
Java's exception handling mechanism (i.e., try-catch blocks).
Interview Question:
You said:
first explain me all the topics related to this with example eplain example also how it works
in briefly for understanding
ChatGPT said:
ChatGPT
Here’s a brief explanation of each topic related to exceptions in Java, with examples and a
simple breakdown of how they work.
An exception is an event that disrupts the normal flow of a program. It is used to signal that
something unexpected has happened, which requires special handling.
Example:
java
Copy code
public class Test {
public static void main(String[] args) {
int result = 10 / 0; // Division by zero will cause an
ArithmeticException
}
}
Checked Exceptions: These exceptions are checked at compile time, and the
programmer must handle them (e.g., IOException, SQLException).
Unchecked Exceptions: These exceptions are not checked at compile time and
usually occur due to programming errors (e.g., NullPointerException,
ArrayIndexOutOfBoundsException).
Example of Checked Exception (IOException):
java
Copy code
import java.io.*;
How it works: The program attempts to open a file that doesn’t exist, which causes a
FileNotFoundException. Since it’s a checked exception, we need to declare throws
IOException in the method signature.
java
Copy code
public class Test {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws
NullPointerException
}
}
In Java, all exceptions are part of a hierarchy rooted in the Throwable class:
java
Copy code
try {
throw new OutOfMemoryError("Memory overflow");
} catch (Error e) {
System.out.println("Caught an error: " + e.getMessage());
}
How it works: Errors usually indicate unrecoverable conditions and are not typically
handled in Java code.
java
Copy code
public class Test {
public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
older");
}
}
How it works: The method checkAge explicitly throws an exception if the age is less
than 18.
Example of throws:
java
Copy code
public class Test {
public void readFile() throws IOException {
FileReader reader = new FileReader("nonexistentfile.txt");
}
5. Try-Catch Block
The try-catch block is used to handle exceptions. The code that might throw an exception
goes inside the try block, and the exception is handled inside the catch block.
Example:
java
Copy code
public class Test {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
6. Finally Block
The finally block is used to execute code that must always run, regardless of whether an
exception occurred or not (e.g., closing resources).
Example:
java
Copy code
public class Test {
public static void main(String[] args) {
try {
int result = 10 / 2; // No exception occurs
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("This will always execute.");
}
}
}
How it works: The finally block runs regardless of whether an exception was
thrown or not, ensuring cleanup actions (like closing resources) are performed.
7. Custom Exceptions
You can create your own exceptions by extending the Exception class (for checked
exceptions) or RuntimeException class (for unchecked exceptions).
Example:
java
Copy code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
8. Multi-Catch in Java
Introduced in Java 7, the multi-catch feature allows you to catch multiple exceptions in a
single catch block.
Example:
java
Copy code
public class Test {
public static void main(String[] args) {
try {
String str = null;
int result = Integer.parseInt("abc"); // Causes
NumberFormatException
} catch (NullPointerException | NumberFormatException e) {
System.out.println("Caught an exception: " +
e.getMessage());
}
}
}
9. Rethrowing Exceptions
Example:
java
Copy code
public class Test {
public void methodA() throws IOException {
try {
throw new IOException("File not found");
} catch (IOException e) {
throw new RuntimeException("Wrapped IOException", e); //
Rethrow as RuntimeException
}
}
Example:
java
Copy code
import java.io.*;
How it works: The BufferedReader is automatically closed when the try block
completes, even if an exception occurs.
Example:
java
Copy code
// Using throw to explicitly throw an exception
public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
older");
}
}
5. Try-Catch Block
Example:
java
Copy code
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
6. Finally Block
Example:
java
Copy code
try {
// Code that might throw an exception
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("This will always execute.");
}
7. Custom Exceptions
Example:
java
Copy code
// Custom checked exception
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
8. Multi-Catch in Java
Example:
java
Copy code
try {
int result = Integer.parseInt("abc"); // Causes
NumberFormatException
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
9. Rethrowing Exceptions
Example:
java
Copy code
try {
throw new IOException("File not found");
} catch (IOException e) {
throw new RuntimeException("Wrapped IOException", e); // Rethrow
as RuntimeException
}
Example:
java
Copy code
try (BufferedReader reader = new BufferedReader(new
FileReader("file.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Example:
java
Copy code
// Using throw
throw new IllegalArgumentException("Invalid argument");
java
Copy code
try {
int result = Integer.parseInt("abc");
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
Example:
java
Copy code
public void processData() throws IOException, SQLException {
// Code that can throw multiple exceptions
}
Example:
java
Copy code
public void checkEligibility(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
older");
}
}
Example:
java
Copy code
// Using throw
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
older");
}
}
Example:
java
Copy code
if (myObject != null) {
myObject.someMethod();
}
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("This will always execute.");
}
Example:
java
Copy code
public void recursiveMethod() {
recursiveMethod(); // This will cause a StackOverflowError
}
ERROR
1. What are Errors in Java?
Q: What are errors in Java, and how do they differ from exceptions?
A:
Errors in Java represent serious problems that typically cannot be handled by the
application. They extend the Error class, which is a subclass of Throwable. Errors
are generally caused by JVM-related issues, such as a lack of memory or a system
failure. Unlike exceptions (which can be caught and handled), errors are generally not
meant to be caught because they usually indicate severe conditions that prevent the
application from continuing to run. Common examples of errors include
OutOfMemoryError, StackOverflowError, and VirtualMachineError.
Key Difference:
o Exceptions: These are conditions that a program can handle. They can be
either checked (require handling) or unchecked (don't require handling).
o Errors: These represent serious issues, often related to the JVM or system,
and are usually not recoverable by the program.
java
Copy code
public class MemoryTest {
public static void main(String[] args) {
int[] arr = new int[Integer.MAX_VALUE]; // This
might throw OutOfMemoryError
}
}
java
Copy code
public class RecursionTest {
public static void recursiveMethod() {
recursiveMethod(); // This will cause
StackOverflowError due to infinite recursion
}
java
Copy code
try {
throw new StackOverflowError("This is a stack overflow error");
} catch (StackOverflowError e) {
System.out.println("Caught an error: " + e.getMessage());
}
However, it’s important to note that this is not a good practice in real-world
applications.
Key Point:
While exceptions can be caught and handled, errors typically cannot be handled and
are not meant to be recovered from. In cases of errors, the best course of action is to
allow the JVM to handle the termination.
java
Copy code
try {
// Simulating an OutOfMemoryError
int[] arr = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
System.out.println("Caught OutOfMemoryError: " + e.getMessage());
}
Note: It’s best to use this approach only for debugging or specific cases where you
are trying to handle resource issues.
6. How to prevent StackOverflowError in Java?
Example:
java
Copy code
public class RecursionTest {
// Add a base case to prevent infinite recursion
public static void safeRecursiveMethod(int count) {
if (count > 0) {
safeRecursiveMethod(count - 1);
}
}
Exceptions that must be handled at compile-time are called checked exceptions in Java.
These exceptions must be either caught using a try-catch block or declared using throws
in the method signature, otherwise, the program will not compile.
Exception Description
Occurs when an I/O operation fails (e.g., reading a file that doesn’t
IOException
exist).
SQLException Occurs when there’s an issue with database operations.
FileNotFoundException Thrown when trying to access a file that does not exist.
InterruptedException Occurs when a thread is interrupted while waiting/sleeping.
This catches and handles the exception so the program can continue running.
import java.io.*;
try {
System.out.println(reader.readLine());
reader.close();
} catch (IOException e) {
If a method does not want to handle a checked exception, it can declare it using throws,
passing the responsibility to the caller.
import java.io.*;
System.out.println(reader.readLine());
reader.close();
try {
readFile();
} catch (IOException e) {
Answer:
Keyword Description
throw Used to manually throw an exception inside a method or block.
throws
Declares that a method might throw one or more exceptions, passing
responsibility to the caller.
Example:
Using throw:
java
CopyEdit
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("You must be 18 or older!");
}
System.out.println("Access granted!");
}
Using throws:
java
CopyEdit
import java.io.*;
Answer:
Example:
java
CopyEdit
public class MultiCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
String str = null;
System.out.println(str.length()); // NullPointerException
} catch (ArithmeticException | NullPointerException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}
Answer:
Example:
java
CopyEdit
public class UncaughtExceptionExample {
public static void divide(int a, int b) {
int result = a / b; // Division by zero (ArithmeticException)
}
🔴 Output:
php
CopyEdit
Exception in thread "main" java.lang.ArithmeticException: / by zero
at UncaughtExceptionExample.divide(UncaughtExceptionExample.java:5)
at UncaughtExceptionExample.main(UncaughtExceptionExample.java:9)
Answer:
Exception propagation is the process where an exception moves up the call stack if not
caught in the current method.
Example:
java
CopyEdit
public class PropagationExample {
public static void methodA() {
int result = 10 / 0; // ArithmeticException
}
🛑 The exception propagates from methodA() → methodB() → main(), and since it's not
caught, the program crashes.
java
CopyEdit
public class FixedPropagationExample {
public static void methodA() {
int result = 10 / 0; // ArithmeticException
}
public static void methodB() {
try {
methodA();
} catch (ArithmeticException e) {
System.out.println("Exception caught in methodB: " +
e.getMessage());
}
}
🔹 Output:
pgsql
CopyEdit
Exception caught in methodB: / by zero
Answer:
Yes! A try block can have multiple catch blocks, each handling a different exception type.
The first matching catch block executes, and others are ignored.
Example:
java
CopyEdit
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds!");
} catch (Exception e) {
System.out.println("Some other exception occurred.");
}
}
}
✔ Output:
pgsql
CopyEdit
Array index is out of bounds!
Answer:
Keyword Meaning
final Used for constants, methods, and classes to prevent modification.
finally A block that always executes after try-catch, used for cleanup.
finalize() A method called by the Garbage Collector before an object is destroyed.
Example of finally:
java
CopyEdit
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught.");
} finally {
System.out.println("Finally block always executes.");
}
}
}
✔ Output:
scss
CopyEdit
Exception caught.
Finally block always executes.
Answer:
Normally, the finally block always executes, but there are two cases where it might be
skipped:
java
CopyEdit
public class SkipFinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try.");
System.exit(0); // Terminates program
} finally {
System.out.println("Finally will not execute.");
}
}
}
✔ Output:
cpp
CopyEdit
Inside try.
⛔ The finally block does not execute because System.exit(0) immediately terminates
the program.
Answer:
Example:
java
CopyEdit
public class FinallyExceptionExample {
public static void main(String[] args) {
try {
System.out.println("Try block executed.");
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Catch block executed.");
} finally {
System.out.println("Finally block executed.");
int x = 10 / 0; // Another ArithmeticException
}
}
}
🔴 Output:
vbnet
CopyEdit
Try block executed.
Catch block executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyExceptionExample.main(FinallyExceptionExample.java:12)
💡 Solution: Wrap finally block code inside a try-catch to prevent exceptions from hiding
previous errors.
Answer:
The finally block ensures that some code executes even if no exception occurs.
Example:
java
CopyEdit
public class TryWithoutCatch {
public static void main(String[] args) {
try {
System.out.println("Inside try block.");
} finally {
System.out.println("Finally block executed.");
}
}
}
✔ Output:
scss
CopyEdit
Inside try block.
Finally block executed.
📌 Note: Without a finally, a try block alone is invalid and results in a compilation error.
Answer:
This is useful when a method catches an exception but wants to pass it to the caller.
Example:
java
CopyEdit
public class RethrowExample {
public static void methodA() throws Exception {
try {
throw new Exception("Original Exception");
} catch (Exception e) {
System.out.println("Exception caught in methodA.
Rethrowing...");
throw e; // Rethrow exception
}
}
✔ Output:
php
CopyEdit
Exception caught in methodA. Rethrowing...
Exception caught in main: Original Exception
📌 Note: If you want to modify the exception, use throw new Exception(e).
Q11: What happens if an exception occurs in both try and finally blocks?
Answer:
If an exception occurs in both the try and finally blocks, the exception in finally
overrides the one in try.
The original exception is lost unless explicitly handled.
Example:
java
CopyEdit
public class ExceptionInFinally {
public static void main(String[] args) {
try {
System.out.println("Try block executed.");
int result = 10 / 0; // ArithmeticException
} finally {
System.out.println("Finally block executed.");
int x = 10 / 0; // Another ArithmeticException
}
}
}
🔴 Output:
vbnet
CopyEdit
Try block executed.
Finally block executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionInFinally.main(ExceptionInFinally.java:9)
Answer:
Example:
java
CopyEdit
public class CatchThrowableExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (Throwable t) { // Catching Throwable
System.out.println("Caught Throwable: " + t);
}
}
}
✔ Output:
csharp
CopyEdit
Caught Throwable: java.lang.ArithmeticException: / by zero
📌 Best Practice: Catch Exception, not Throwable, unless there's a strong reason to catch
serious errors.
Answer:
java
CopyEdit
import java.io.*;
java
CopyEdit
import java.io.*;
✔ Benefits of try-with-resources:
✅ No need for explicit close() calls.
✅ Prevents resource leaks.
✅ Cleaner and shorter code.
Answer:
java
CopyEdit
class AgeException extends Exception { // Custom checked exception
public AgeException(String message) {
super(message);
}
}
✔ Output:
vbnet
CopyEdit
Caught custom exception: Age must be 18 or older.
📌 Use Cases: Custom exceptions help make errors more meaningful and easier to debug.
Example:
java
CopyEdit
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
Output:
pgsql
CopyEdit
Caught exception: This is a custom exception
Since an exception was thrown inside the try block, execution of the try block
stops immediately.
The Java runtime searches for a matching catch block to handle the exception.
Since MyCustomException was thrown, and there is a matching catch block, the
catch block executes.
Inside the catch block, e.getMessage() is called.
Since we stored the message "This is a custom exception" using
super(message), getMessage() returns this string.
The message is printed:
Caught exception: This is a custom exception
After executing the catch block, the program completes execution successfully.
Since the exception was handled, it does not crash the program.
Flowchart Representation
Final Output
Caught exception: This is a custom exception