Day 7: Exception Handling & Arrays
� Learning Roadmap
Day 1-6 (Core OOP) → Day 7 (Exception Handling & Arrays) → Day 8 (Collections Framework)
↓
You are here
� Learning Objectives
By the end of this session, you will be able to: - Understand and handle excep-
tions using try-catch-finally blocks. - Create and throw custom exceptions.
- Differentiate between checked and unchecked exceptions. - Understand the
use of the final keyword. - Declare, initialize, and manipulate arrays. - Use
ArrayList and LinkedList for dynamic data storage. - Understand the trade-
offs between ArrayList and LinkedList.
� Time Allocation
• Exception Handling & final keyword (45 minutes)
• Arrays & Lists (45 minutes)
Session 1: Exception Handling & final Keyword (45 min-
utes)
1. Java Exception Handling
What is an Exception? An exception is an event that disrupts the normal
flow of a program. When an error occurs within a method, the method creates
an exception object and hands it off to the runtime system.
Exception Hierarchy:
Throwable
/ \
Error Exception
/ \
Checked Unchecked (RuntimeException)
(e.g., IOException) (e.g., NullPointerException)
Why Handle Exceptions?
• To maintain the normal flow of the application.
• To prevent the program from terminating abruptly.
• To provide meaningful error messages to the user.
1
2. The try-catch Block
The try-catch block is used to enclose code that might throw an exception and
handle it.
public class TryCatchExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
int result = 10 / 0;
[Link]("This will not be printed.");
} catch (ArithmeticException e) {
// Code to handle the exception
[Link]("Error: Cannot divide by zero.");
[Link]("Exception details: " + [Link]());
}
[Link]("Program continues after handling the exception.");
}
}
Multiple Catch Blocks: You can use multiple catch blocks to handle different
types of exceptions.
try {
int[] a = new int[5];
a[5] = 30 / 0; // Generates two exceptions
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out Of Bounds Exception occurred.");
} catch (Exception e) {
[Link]("Parent Exception occurred.");
}
3. The finally Block
The finally block is always executed, whether an exception is handled or not.
It’s used for cleanup activities like closing files or database connections.
public class FinallyExample {
public static void main(String[] args) {
try {
int data = 25 / 5;
[Link](data);
} catch (NullPointerException e) {
[Link](e);
} finally {
[Link]("The 'finally' block is always executed.");
2
}
[Link]("Rest of the code...");
}
}
4. The throw and throws Keywords
throw The throw keyword is used to explicitly throw an exception from a
method or a block of code.
public class ThrowExample {
public static void validate(int age) {
if (age < 18) {
// Throw an instance of ArithmeticException
throw new ArithmeticException("Person is not eligible to vote");
} else {
[Link]("Person is eligible to vote");
}
}
public static void main(String[] args) {
try {
validate(13);
} catch (ArithmeticException e) {
[Link]("Caught exception: " + [Link]());
}
}
}
throws The throws keyword is used in a method signature to declare the
exceptions that might be thrown by the method.
import [Link];
class ThrowsExample {
// Declare that this method can throw an IOException
void myMethod() throws IOException {
throw new IOException("device error");
}
public static void main(String[] args) {
ThrowsExample obj = new ThrowsExample();
try {
[Link]();
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
3
}
}
5. Custom Exceptions
You can create your own exception classes by extending the Exception class.
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionTest {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote");
}
}
public static void main(String[] args) {
try {
validate(13);
} catch (InvalidAgeException ex) {
[Link]("Caught the exception: " + [Link]());
}
}
}
6. The final Keyword
The final keyword is a non-access modifier used for classes, methods, and
variables.
• Final Variable: Makes the variable a constant. Its value cannot be
changed.
final int MAX_VALUE = 100;
// MAX_VALUE = 150; // This would cause a compile error
• Final Method: Prevents the method from being overridden by a sub-
class.
class Base {
final void show() {
[Link]("This is a final method.");
}
}
4
class Derived extends Base {
// void show() { } // Compile error: cannot override final method
}
• Final Class: Prevents the class from being extended (inherited).
final class FinalClass {
// ...
}
// class SubClass extends FinalClass { } // Compile error
Session 2: Arrays & Lists (45 minutes)
1. Arrays
An array is a container object that holds a fixed number of values of a single
type. The length of an array is established when the array is created.
Declaration and Initialization
// Declaration
int[] anArray;
// Initialization with size
anArray = new int[10];
// Declaration and initialization in one line
String[] names = {"Alice", "Bob", "Charlie"};
Accessing Elements Array elements are accessed by their index, starting
from 0.
int[] numbers = {10, 20, 30, 40, 50};
[Link]("First element: " + numbers[0]); // 10
[Link]("Third element: " + numbers[2]); // 30
numbers[1] = 25; // Modify an element
Iterating Over an Array
String[] fruits = {"Apple", "Banana", "Orange"};
// Using a for loop
for (int i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
5
// Using an enhanced for-each loop
for (String fruit : fruits) {
[Link](fruit);
}
2. ArrayList
ArrayList is a resizable array implementation from the Collections Framework.
It provides dynamic arrays in Java.
Creating an ArrayList
import [Link];
import [Link];
// Create an ArrayList of Strings
List<String> animals = new ArrayList<>();
Common ArrayList Operations
List<String> animals = new ArrayList<>();
// Add elements
[Link]("Lion");
[Link]("Tiger");
[Link]("Bear");
[Link]("ArrayList: " + animals); // [Lion, Tiger, Bear]
// Get an element
String firstAnimal = [Link](0);
[Link]("First animal: " + firstAnimal); // Lion
// Set an element
[Link](1, "Zebra");
[Link]("Modified ArrayList: " + animals); // [Lion, Zebra, Bear]
// Remove an element
[Link](2);
[Link]("After removal: " + animals); // [Lion, Zebra]
// Get size
[Link]("Size: " + [Link]()); // 2
3. LinkedList
LinkedList is another implementation of the List interface. It stores elements
in a doubly-linked list structure. It’s efficient for insertions and deletions.
6
Creating a LinkedList
import [Link];
import [Link];
List<String> cars = new LinkedList<>();
Common LinkedList Operations LinkedList supports all the standard
List operations like add, get, remove, etc. It also provides additional methods
for adding/removing from the beginning or end.
LinkedList<String> cars = new LinkedList<>();
[Link]("Volvo");
[Link]("BMW");
// Add to the beginning
[Link]("Ford");
// Add to the end
[Link]("Mazda");
[Link]("LinkedList: " + cars); // [Ford, Volvo, BMW, Mazda]
// Remove from the beginning
[Link]();
// Remove from the end
[Link]();
[Link]("After removal: " + cars); // [Volvo, BMW]
4. ArrayList vs. LinkedList
The choice between ArrayList and LinkedList depends on the specific use
case.
Feature ArrayList LinkedList
Internal Structure Dynamic Array Doubly-Linked List
Element Access (get) Fast (O(1)) Slow (O(n))
Insertion/Deletion Slow (O(n)) Fast (O(1)) once node is
(Middle) found
Insertion/Deletion Fast (Amortized O(1)) Fast (O(1))
(End)
Memory Overhead Lower Higher (stores pointers)
� When to use which? Answer
7
• Use ArrayList when:
– You have frequent random access operations (using get(index)).
– You have more read operations than write (insertion/deletion) oper-
ations.
– You are adding/removing elements mostly at the end of the list.
• Use LinkedList when:
– You have frequent insertion and deletion operations, especially in the
middle of the list.
– You don’t need random access to elements.
– You need to use it as a Queue or Deque, as it implements these
interfaces.
� Recap
In this session, we covered:
1. Exception Handling
• Using try-catch-finally to manage errors gracefully.
• Creating and using custom exceptions for application-specific errors.
• Understanding the difference between throw and throws.
2. final Keyword
• Creating constants, final methods, and final classes.
3. Arrays and Lists
• Using fixed-size arrays for simple data collections.
• Using ArrayList for fast random access and dynamic resizing.
• Using LinkedList for fast insertions and deletions.
� Next Steps
In the next session, we’ll dive deeper into the Java Collections Frame-
work, exploring: - Maps (HashMap, TreeMap, LinkedHashMap) - Sets (HashSet,
TreeSet, LinkedHashSet) - Legacy collections and other important concepts.