1. What is the purpose of Exception Handling in Java?
Purpose of Exception Handling in Java
Exception handling in Java is a mechanism used to handle runtime errors in a controlled and efficient
way. The primary goals of exception handling are:
1. Ensuring Program Continuity – Instead of crashing, the program can catch and handle
exceptions, allowing it to continue execution or terminate gracefully.
2. Enhancing Debugging – By using exception messages and stack traces, developers can quickly
identify and fix issues in their code.
3. Maintaining Code Readability – Separating error-handling logic from the main business logic
improves code clarity.
4. Encapsulating Error-Handling Logic – Java provides a structured way to handle errors using try,
catch, finally, and throw, making error handling consistent and maintainable.
5. Handling Different Types of Errors – Java provides a rich exception hierarchy, allowing the
handling of different types of errors such as:
o Checked Exceptions (e.g., IOException) – Must be handled explicitly.
o Unchecked Exceptions (e.g., NullPointerException) – Indicate programming errors.
o Errors (e.g., OutOfMemoryError) – Indicate severe issues typically beyond the
programmer’s control.
Example of Exception Handling in Java
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
System.out.println("Execution completed.");
Key Exception Handling Keywords in Java
1. try – Defines a block of code to test for exceptions.
2. catch – Handles specific exceptions.
3. finally – A block that always executes, used for cleanup.
4. throw – Used to explicitly throw an exception.
5. throws – Declares exceptions that a method might throw.
2. Differentiate between checked and unchecked exceptions.
Difference Between Checked and Unchecked Exceptions in Java
Feature Checked Exceptions Unchecked Exceptions
Exceptions that are checked at compile Exceptions that occur at runtime and are not
Definition
time. checked at compile time.
Must be either handled using try-catch Handling is optional; the program can still
Handling
or declared using throws. compile without handling them.
When They
During compile time. During program execution (runtime).
Occur
Subclasses of Exception (except
Extends Subclasses of RuntimeException.
RuntimeException).
NullPointerException,
IOException, SQLException,
Examples ArrayIndexOutOfBoundsException,
FileNotFoundException.
ArithmeticException.
Used for conditions that a well-written
Typically caused by programming errors (e.g.,
Usage application should anticipate and
accessing an invalid index in an array).
recover from.
Example of Checked Exception (IOException)
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file); // May cause FileNotFoundException (checked)
} catch (IOException e) {
System.out.println("File not found or cannot be read.");
Example of Unchecked Exception (NullPointerException)
public class UncheckedExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Causes NullPointerException (unchecked)
3. Differentiate between throw and throws in Exception Handling.
Difference Between throw and throws in Exception Handling
Feature throw throws
Used to declare exceptions that a
Definition Used to explicitly throw an exception.
method may throw.
Usage Inside a method or block. In the method signature.
One or more exception class
Followed By An instance of an exception.
names.
Does not handle exceptions but
Immediately terminates execution and
Execution Flow informs the caller about possible
transfers control to the nearest catch block.
exceptions.
throw new NullPointerException("Null value public void readFile() throws
Example Exceptions
found"); IOException {}
Feature throw throws
Extends Can be used to throw both checked and Typically used for checked
RuntimeException? unchecked exceptions. exceptions.
Example of throw
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
System.out.println("Valid age.");
public static void main(String[] args) {
validateAge(16); // Throws an IllegalArgumentException
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above
Example of throws
import java.io.IOException;
public class ThrowsExample {
public static void readFile() throws IOException {
throw new IOException("File not found");
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("Handled Exception: " + e.getMessage());
Output:
Handled Exception: File not found
Key Takeaways
• Use throw to explicitly generate an exception.
• Use throws to declare exceptions in a method signature.
• throw follows with an object of an exception while throws follows with exception class names.