1. What is Exception Handling in Java?
● D efinition: Exception Handling in Java is a mechanismto handle runtime errors,
ensuring the normal flow of the application.
● Exceptions: These are events that disrupt the normalflow of a program. For
example, accessing an invalid array index or dividing by zero.
● Key Concepts:
○ Try-catch blocks: To handle exceptions.
○ Throw and Throws: To explicitly throw exceptions anddeclare them.
○ Finally block: To execute code regardless of whetheran exception occurred.
2. Types of Exceptions in Java
(a) Checked Exceptions
T
● hese are exceptions checked at compile-time.
● Examples:
○
IOException
○ SQLException
xample:
E
Java code
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
(b) Unchecked Exceptions
T
● hese occur during runtime and are not checked at compile-time.
● Examples:
○
ArithmeticException
○NullPointerException
○ ArrayIndexOutOfBoundsException
xample:
E
Java code
public class UncheckedExceptionExample {
public static void main(String[] args) {
int num = 10 / 0; // Causes ArithmeticException
}
}
(c) Errors
E
● rrors are serious issues that the application cannot recover from.
● Examples:
○
StackOverflowError
○ OutOfMemoryError
3. Exception Hierarchy
Java has a predefined class hierarchy for exceptions:
● Root:
Throwable
○ Error: Irrecoverable issues (e.g., JVM errors).
○ Exception: Recoverable conditions:
■ Checked exceptions ( IOException ,
SQLException).
■ Unchecked exceptions (
ArithmeticException,
NullPointerException).
4. Try-Catch Block
yntax:
S
Java code
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle exception
}
xample:
E
Java code
public class TryCatchExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Finally Block
A
● lways executes whether an exception occurs or not.
● Used for cleanup operations like closing files or database connections.
xample:
E
Java code
public class FinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
6. Throw and Throws
(a) Throw
● Used to explicitly throw an exception.
yntax:
S
Java code
throw new ExceptionType("Exception message");
xample:
E
Java code
public class ThrowExample {
public static void main(String[] args) {
validateAge(15);
}
static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
above");
}
System.out.println("Valid age");
}
}
(b) Throws
● Used in method signatures to declare exceptions that the method might throw.
yntax:
S
Java code
returnType methodName() throws ExceptionType1, ExceptionType2 {
// Method code
}
xample:
E
Java code
import java.io.*;
public class ThrowsExample {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("nonexistent.txt");
}
}
7. Custom Exceptions
W
● e can create user-defined exceptions by extending the
Exceptionclass.
● Steps:
1. Extend the Exceptionclass (or
RuntimeExceptionforunchecked
exceptions).
2. Provide a constructor for custom messages.
xample:
E
Java code
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Exception: " + e.getMessage());
}
}
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or
above");
}
System.out.println("Valid age");
}
}
8. Multiple Catch Blocks
A
●
tryblock can be followed by multiple
catchblocksto handle different exceptions.
● Rule: More specific exceptions should come beforemore general ones.
xample:
E
Java code
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = new int[5];
arr[5] = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException
caught: " + e.getMessage());
}
}
}
9. Try-With-Resources (Automatic Resource Management)
Introduced inJava 7, it ensures resources are closedautomatically after use.
●
● Works with classes implementing AutoCloseableor Closeableinterfaces.
xample:
E
Java code
import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("test.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
}
10. Exception Propagation
● Exceptions are propagated from one method to another unless handled explicitly.
xample:
E
Java code
public class ExceptionPropagationExample {
public static void main(String[] args) {
try {
method1();
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
}
static void method1() {
method2();
}
static void method2() {
int num = 10 / 0; // Causes ArithmeticException
}
}
11. Best Practices
1. Always usespecific exceptionsinstead of genericones like
Exceptionor
Throwable
.
.
2 void swallowing exceptions (empty catch blocks).
A
3. Usefinallyor try-with-resources for resource cleanup.
4. Don't overuse custom exceptions; only create them when necessary.
5. Handle exceptions gracefully to avoid application crashes.
Common Interview Questions on Exception Handling in Java
1. What is the difference between
throwand
throws?
Aspect throw throws
Purpose sed to explicitly throw an
U eclares exceptions that a method
D
exception. can throw.
Usage Inside the method body. In the method signature.
umber of
N an throw only one exception
C an declare multiple exceptions
C
Exceptions at a time. separated by commas.
Example throw new oid method() throws
v
Exception("Error"); IOException {}
2. What is the difference between checked and unchecked exceptions?
Aspect Checked Exceptions Unchecked Exceptions
Definition xceptions checked at
E Exceptions checked at runtime.
compile-time.
Inheritance Subclasses of
Exception
, Subclasses of
excluding
RuntimeException
. RuntimeException
.
Examples IOException,
SQLException ullPointerException,
N
ArithmeticException
andling
H Must be handled using o handling required by the
N
Requirement try-catchor declared using compiler.
throws.
3. Can you explain the use of the
finallyblock?
● T hefinallyblock is used forcleanup operations, such as closing files, releasing
database connections, etc.
● Italways executesafter the
tryand
catchblocks,regardless of whether an
exception occurred or was handled.
xample:
E
Java code
public class FinallyExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
aught: / by zero
C
Finally block executed.
4. What is the difference between
final,
finally, and
finalize()
?
Keyword/Method Purpose
final
keyword used to declare constants, prevent method overriding, or
A
prevent inheritance.
finally
A block used for cleanup operations in exception handling.
finalize()
method invoked by the garbage collector before an object is
A
destroyed (deprecated in Java 9).
5. What happens if an exception is thrown in a
finallyblock?
● If the
finallyblock itself throws an exception, it will override any previously thrown
exception from the
tryorcatchblocks.
xample:
E
Java code
public class FinallyExceptionExample {
public static void main(String[] args) {
try {
throw new ArithmeticException("Exception from try");
} finally {
throw new NullPointerException("Exception from
finally");
}
}
}
Output:
xception in thread "main" java.lang.NullPointerException: Exception
E
from finally
6. Can we have a
tryblock without a
catchblock?
● Yes, but it must be followed by a
finallyblock.
xample:
E
Java code
public class TryWithoutCatchExample {
public static void main(String[] args) {
try {
System.out.println("Try block executed");
} finally {
System.out.println("Finally block executed");
}
}
}
Output:
ry block executed
T
Finally block executed
7. How are exceptions handled in multithreaded applications?
● E ach thread has its owncall stack, and exceptions must be handled within the
thread itself.
● If an exception occurs in one thread, it doesn't affect other threads.
xample:
E
Java code
public class MultiThreadExceptionExample extends Thread {
public void run() {
try {
System.out.println("Thread running: " +
Thread.currentThread().getName());
int num = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught in thread: " +
Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MultiThreadExceptionExample t1 = new
MultiThreadExceptionExample();
t1.start();
}
}
8. What are common mistakes in exception handling?
. Catching generic exceptionslike
1 Exceptionor
Throwable.
Java code
/ Bad Practice
/
try {
int num = 10 / 0;
} catch (Exception e) {
System.out.println("Exception caught");
}
. Empty catch blocks.
2
Java code
/ Bad Practice
/
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
// No error message
}
3. Ignoring exceptions or logging them without actionable messages.