1. What is Exception?
Explain the following keywords with respect to exception handling in Java
An exception in Java is an unexpected event or error that occurs during program execution.
Exceptions disrupt the normal flow of the program.
i) try:
The 'try' block contains code that might throw an exception. If an exception occurs, control moves to
the catch block.
Example:
public class TryExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("Division by zero!");
}
}
}
ii) catch:
The 'catch' block handles exceptions thrown by the 'try' block. Each catch block can handle specific
exceptions.
Example:
public class CatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Invalid index!");
}
}
}
2. What is Nested Try? Explain with an Example Program
Nested try refers to a try block inside another try block. It is used to handle exceptions at different
levels.
Example:
public class NestedTryExample {
public static void main(String[] args) {
try {
try {
int[] arr = {1, 2};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: Invalid index");
}
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Outer catch: Division by zero");
}
}
}
3. Explain `throw` and `throws` keywords
i) throw:
The 'throw' keyword is used to explicitly throw an exception.
Example:
public class ThrowExample {
static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
}
public static void main(String[] args) {
validateAge(16);
}
}
ii) throws:
The 'throws' keyword is used to declare exceptions in the method signature.
Example:
public class ThrowsExample {
static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found");
}
}
}
4. Illustrate Multiple Catch Clauses with a Suitable Example
Multiple catch blocks handle different types of exceptions.
Example:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2};
[Link](arr[5]);
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Invalid index");
} catch (ArithmeticException e) {
[Link]("Division by zero");
}
}
}
5. What is `finally`? Explain with a Suitable Example
The 'finally' block contains code that executes regardless of whether an exception occurs or not.
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception: Division by zero");
} finally {
[Link]("Finally block executed");
}
}
}