Group 8
Andrei B. Manzanes
BSIT-3C
7. How can exception handling be integrated into methods to create robust and fault-
tolerant Java applications?
1. Encapsulate Risky Code with try-catch Statements
When a method involves operations that could potentially fail—like accessing files, databases, or
performing conversions—wrap these parts with try-catch blocks to gracefully handle the
errors.
public void loadFile(String filePath) {
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = [Link]();
[Link](line);
[Link]();
} catch (FileNotFoundException fnfe) {
[Link]("Unable to locate the file: " + [Link]());
} catch (IOException ioe) {
[Link]("Issue encountered while reading: " + [Link]());
}
2. Propagate Exceptions with throws
If a method can't resolve a certain issue on its own, let the caller deal with it by specifying the
exception in the method signature.
public void processInput(String inputFile) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// Further processing here
3. Define Custom Exceptions for Specific Scenarios
To represent application-specific errors, you can design your own exception classes. This
improves code clarity and control.
class GradeOutOfRangeException extends Exception {
public GradeOutOfRangeException(String detail) {
super(detail);
public void validateGrade(int score) throws GradeOutOfRangeException {
if (score < 0 || score > 100) {
throw new GradeOutOfRangeException("Score must be within 0 to 100.");
}
4. Ensure Cleanup with finally
Use the finally block to release resources—such as file handles or connections—regardless of
whether an exception was thrown.
FileInputStream input = null;
try {
input = new FileInputStream("[Link]");
// process the file
} catch (IOException ex) {
[Link]("File error: " + [Link]());
} finally {
try {
if (input != null) [Link]();
} catch (IOException e) {
[Link]("Couldn't close the file.");
5. Be Specific When Catching Exceptions
Avoid catching general exceptions unless absolutely necessary. It’s more effective to handle only
the exceptions you expect.
// ❌ Not recommended
catch (Exception e) { ... }
// ✅ Preferred approach
catch (NumberFormatException nfe) { ... }
6. Use Logging for Better Diagnostics
Instead of printing errors to the console, use a logging framework like Log4j or
[Link] to track problems in production environments.