Week 11: Java – Exception Handling
Q1. Division with Exception Handling
Objective: Safely handle division by zero using try-catch.
import java.util.Scanner;
class q1 {
public Integer divide(int a, int b) {
try {
return a / b; // may throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
return null; // return null instead of crashing
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
q1 calc = new q1();
System.out.print("Numerator: ");
int numerator = sc.nextInt();
System.out.print("Denominator: ");
int denominator = sc.nextInt();
Integer result = calc.divide(numerator, denominator);
if (result != null) {
System.out.println("Result: " + result);
} else {
System.out.println("Program continues safely.");
}
sc.close();
}
}
Key Points:
try-catchhandles runtime exceptions (ArithmeticException).- Program does not crash on division by zero.
- Returning
nullallows the program to continue safely.
Q2. File Reading with Checked Exceptions
Objective: Handle both checked (IOException) and unchecked (IllegalArgumentException) exceptions.
import java.io.IOException;
class FileReaderUtility {
public static void readFile(String fileName) throws IOException {
if (fileName.isEmpty()) {
throw new IllegalArgumentException("Filename cannot be empty.");
}
if (fileName.equals("missing.txt")) {
throw new IOException("File not found.");
}
System.out.println("Reading file: " + fileName);
}
}
public class q2 {
public static void main(String[] args) {
String[] files = {"data.txt", "", "missing.txt"};
for (String file : files) {
try {
FileReaderUtility.readFile(file);
}
catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
finally {
// Optional cleanup can be placed here
}
}
}
}
Key Points:
IOExceptionis a checked exception – must be declared or caught.IllegalArgumentExceptionis unchecked – can occur at runtime.finallyblock executes regardless of exception, useful for cleanup.- Using multiple
catchblocks allows handling different exception types separately.
Week 11 Concepts Summary
-
Try-Catch
-
Wrap risky code in
try. - Handle exceptions in
catch. -
Checked vs Unchecked Exceptions
-
Checked: must be handled (
IOException,FileNotFoundException). - Unchecked: optional handling (
ArithmeticException,IllegalArgumentException). -
Finally Block
-
Executes always, even if exception occurs.
- Often used for closing resources (files, DB connections).
-
Exception Propagation
-
Use
throwsin method signature to propagate exceptions.