errors-in-java-1
errors-in-java-1
(10 minutes)
1. Definition:
o Exceptions are events that disrupt the normal flow of a program’s
execution.
o In Java, exceptions are objects that represent errors or unexpected
events.
2. Purpose of Exceptions:
o To gracefully manage runtime errors.
3. Code Example:
try {
int result = 10 / 0; // Will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
B. Types of Exceptions (20 minutes)
1. Checked Exceptions:
o Must be handled during compile-time.
o Code Example:
import java.io.*;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (IOException e) {
System.out.println("File not found.");
}
}
}
Runtime Exceptions:
Code Example:
public class RuntimeExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws NullPointerException
}
}
Errors:
Try-Catch Blocks:
Finally Block:
Describe how finally ensures execution of cleanup code.
Code Example:
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} finally {
System.out.println("This block always executes.");
}
Custom Exceptions:
Explain how to define and use custom exceptions.
Code Example:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
2. Problem-Solving Task:
o Write a program that takes two integers as input and performs division.
o Ensure the program handles exceptions for division by zero and invalid
inputs.
2. Assignment:
o Write a Java program that reads a file and handles possible exceptions,
including file not found and incorrect file format.
2. Q&A:
o Allow students to ask questions to clarify their understanding.
Materials Needed:
Laptop/PC with Java IDE installed
Projector
Sample Java programs for practice and demonstration