June 2024
EXCEPTIONS IN
Java
JUNE, 2024
CONTENT
Overview of Exceptions
What Is an Exception?
The Catch or Specify Requirement
How to Throw Exceptions
The try-with-resources Statement
Unchecked Exceptions — The
Controversy
Advantages of Exceptions
Summary
JUNE, 2024
Overview of Exceptions
• Java uses exceptions to handle errors and
exceptional events.
• This lesson covers the basics of using exceptions
in Java, including definitions, handling, and best
practices.
JUNE, 2024
What Is an Exception?
Definition:
• An exception is an event that disrupts the normal
flow of a program's instructions.
Types of Exceptions:
• Checked Exceptions: Must be caught or declared.
• Unchecked Exceptions: Runtime exceptions and
errors.
JUNE, 2024
The Catch or Specify
Definition:
Requirement
• If a method can throw a checked exception, it must
either catch the exception or specify it using the throws
keyword.
Example:
public void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
// Read file
}
JUNE, 2024
Catching and Handling
Purpose:
Exceptions
• To handle exceptions where they occur and take
appropriate action.
Syntax:
• Use the try block to wrap code that might throw an
exception.
• Use one or more catch blocks to handle different
exceptions.
JUNE, 2024
The try Block
Usage:
• Encapsulates code that might throw an exception.
Example:
try {
// Code that might throw an exception
int result = 10 / 0;
}
JUNE, 2024
The catch Blocks
Usage:
• Catch blocks handle specific exceptions thrown by the
try block.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} catch (Exception e) {
[Link]("An error occurred");
}
JUNE, 2024
Purpose:
The finally Block
• Executes code regardless of whether an exception was
thrown or not.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("This will always execute");
}
JUNE, 2024
The try-with-resources
Definition:
Statement
• Ensures that each resource is closed at the end of the
statement.
Example:
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
JUNE, 2024
Comprehensive Example
public class ExceptionExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) { Explanation:
[Link](line); • try Block: Opens and reads from a file.
} • catch Blocks: Handles FileNotFoundException and
} catch (FileNotFoundException e) { IOException.
• finally Block: Executes code regardless of exceptions.
[Link]("File not found");
• try-with-resources: Ensures BufferedReader is closed
} catch (IOException e) { automatically.
[Link]("Error reading file");
} finally {
[Link]("Execution complete");
}
}
}
JUNE, 2024
Specifying the Exceptions Thrown by a Method
Purpose:
• Inform callers about exceptions that a method can throw.
Syntax:
• Use the throws keyword in the method signature.
Example:
public void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
// Read file
}
Usage:
• The caller must handle or declare these exceptions.
JUNE, 2024
How to Throw Exceptions
Overview:
• Exceptions are used to handle errors and other
exceptional events in Java.
• Throwing exceptions allows a method to signal an
error condition to its caller.
Syntax:
• throw is used to explicitly throw an exception.
• Syntax: throw new ExceptionType("Error message");
Example:
if (num < 0) {
throw new IllegalArgumentException("Number must be
non-negative.");
}
JUNE, 2024
Throwable Class and Its Subclasses
Hierarchy:
• Throwable is the superclass of all errors and
exceptions.
Subclasses:
• Error: Represents serious problems that a reasonable
application should not catch.
Examples
⚬ OutOfMemoryError
⚬ StackOverflowError
• Exception: Represents conditions that a reasonable
application might want to catch and handle.
Examples
⚬ IOException
⚬ SQLException
JUNE, 2024
Chained Exceptions
Overview:
• Allows one exception to be wrapped in another.
• Helps to preserve the original exception information.
Example:
try {
// Code that throws an exception
} catch (Exception e) {
throw new CustomException("Custom error message",
e);
}
JUNE, 2024
Accessing Stack Trace Information
Method:
• Use getStackTrace() to retrieve stack trace elements.
Example:
try {
// Code that throws an exception
} catch (Exception e) {
StackTraceElement[] elements = [Link]();
for (StackTraceElement element : elements) {
[Link](element);
}
}
JUNE, 2024
Logging API
Overview:
• Use Java's logging API to log exception information.
Example:
import [Link].*;
private static final Logger LOGGER =
[Link]([Link]());
try {
// Code that throws an exception
} catch (Exception e) {
[Link]([Link], "Exception occurred", e);
}
JUNE, 2024
Creating Exception Classes
Steps:
• Define a class that extends Exception or
RuntimeException.
Example:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable
cause) {
super(message, cause);
}
}
JUNE, 2024
Choosing a Superclass
Guidelines:
• Extend Exception for checked exceptions.
• Extend RuntimeException for unchecked exceptions.
Considerations:
• Checked exceptions must be declared in the method
signature.
• Unchecked exceptions do not need to be declared.
JUNE, 2024
Unchecked Exceptions — The Controversy
Overview:
• Debate over the use of unchecked (RuntimeException)
vs. checked exceptions.
Arguments For Unchecked Exceptions:
• Simplify method signatures.
• Reduce boilerplate code.
Arguments Against Unchecked Exceptions:
• Can lead to unhandled exceptions.
• Makes the contract of methods less clear.
JUNE, 2024
Advantages of Exceptions
Error Handling:
• Separates error handling code from regular code.
Propagation:
• Allows errors to be propagated up the call stack.
Type Safety:
• Provides a robust way to handle different types of
errors.
Example:
public void readFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
}
June 2024
thank you